从 javascript 创建的按钮不可点击

问题描述 投票:0回答:1

HTML

<div class="wrapper">
 <div class="bg-backdrop"></div>
</div>

CSS

.wrapper {
  position: relative;
  z-index: 10;
}

.bg-backdrop {
  position: fixed;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
  background-color: black;
  opacity: 0.2;
}

JS

const button = document.createElement("button")
const subject = document.querySelector(".bg-backdrop")

button.textContent = "Register"
subject.insertAdjacentElement("beforebegin",button)

button.addEventListener("click", word)

function word() {
    console.log("It works!")
}

在 javascript 中创建的按钮不起作用,无法单击,并且不显示任何输出

我尝试删除 z-index 但仍然不起作用。同样将按钮元素放在包装器之外,仍然不起作用

javascript html dom
1个回答
1
投票

const button = document.createElement("button")
const subject = document.querySelector(".bg-backdrop")

button.textContent = "Register"
button.setAttribute('style', 'position:relative; z-index: 100;')
subject.insertAdjacentElement("beforebegin", button)

button.addEventListener("click", word)

function word() {
  console.log("It works!", document)
}
.wrapper {
  position: relative;
  z-index: 10;
}

.bg-backdrop {
  position: fixed;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
  background-color: black;
  opacity: 0.2;
}
<div class="wrapper">
  <div class="bg-backdrop"></div>
</div>

const button = document.createElement("button")
const subject = document.querySelector(".bg-backdrop")

button.textContent = "Register"
button.setAttribute('style','position:relative;z-index: 100;')
subject.insertAdjacentElement("beforebegin",button)

button.addEventListener("click", word)

function word() {
    console.log("It works!")
}

只需将此代码添加到 javascript 文件中

将此行添加到第 5 行:

button.setAttribute('style','position:relative; z-index: 100;')

基本上我们必须为按钮添加 z-index 以及使 z-index 起作用的位置。

© www.soinside.com 2019 - 2024. All rights reserved.