从 javascript 创建的按钮不可点击

you*_*hwc 4 html javascript dom

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!")
}
Run Code Online (Sandbox Code Playgroud)
.wrapper {
  position: relative;
  z-index: 10;
}

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

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

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

小智 5

Added this line at line number 5:

button.setAttribute('style','position:relative; z-index: 100;')
Run Code Online (Sandbox Code Playgroud)

Basically we have to add z-index for button and also a position to make z-index work.

button.setAttribute('style','position:relative; z-index: 100;')
Run Code Online (Sandbox Code Playgroud)
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)
}
Run Code Online (Sandbox Code Playgroud)
.wrapper {
  position: relative;
  z-index: 10;
}

.bg-backdrop {
  position: fixed;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
  background-color: black;
  opacity: 0.2;
}
Run Code Online (Sandbox Code Playgroud)