javascript 如何使父div不向子div传递click

drkbr07n  于 2023-02-18  发布在  Java
关注(0)|答案(3)|浏览(221)

我有一个覆盖整个页面的父级<div />。在此父级<div />中,我有一个较小的子级<div />。当父级<div />覆盖子级'时,我不希望子级<div />可单击。

function parentFunction(event) {
  if (document.getElementById("check").checked) {
    event.stopPropagation();
  }
}

function childFunction() {
  alert("CHILD");
}
.child {
  padding: 50px;
  width: 100px;
  height: 100px;
  background-color: hotpink;
  text-align: center;
  cursor: pointer;
}

.parent {
    width: 500px;
    height: 500px;
    filter: blur(2px);
    display: flex;
    justifc-content: center;
    align-items: center;
    align-content: center;
    background-color: lightgray;
}
<body>
  <div
      onclick="parentFunction(event)"
      class="parent">
      <div
          onclick="childFunction()"
          class="child">
          Child
      </div>
  </div>
</body>

Stop propagation:
<input type="checkbox" id="check">
bkkx9g8r

bkkx9g8r1#

这里有一个可能满足您需求的解决方案。
当你点击包含子元素的父元素时,它会告诉你点击了哪个元素,然后你可以 * if * 自己进入你在功能中需要的目标/解决方案。

document.querySelector(".parent").addEventListener("click", parentFunction)
function parentFunction(e) {
  if (document.getElementById("check").checked && e.target == document.querySelector(".child")) {
    e.stopPropagation();
    console.log("EXIT")
    return;
  }
  console.log("PARENT says target is: ", e.target)
}
body {
    display: flex;
    justifc-content: center;
    align-items: center;
    flex: 1;
    width: 100vh;
    height: 100vw;
}
    
.child {
  padding: 50px;
  width: 100px;
  height: 100px;
  background-color: hotpink;
  text-align: center;
  cursor: pointer;
}

.parent {
    width: 500px;
    height: 500px;
    filter: blur(2px);
    display: flex;
    justify-content: center;
    align-items: center;
    align-content: center;
    background-color: lightgray;
cursor:pointer;

}
<body>
  <div
      class="parent">
      <div
          class="child">
          Child
      </div>
  </div>
</body>

Stop propagation:
<input type="checkbox" id="check">
guykilcj

guykilcj2#

如前所述,传播是从子代到父代,而不是父代到子代。
您拥有的可能性:

  • 添加样式指针事件:无到子div

  • 在childFunction()中检查父div是否存在,如果存在则返回;
yks3o0rb

yks3o0rb3#

反过来说,当您点击child时,您不希望事件传播到与之重叠的父节点,因此应该改为:

function parentFunction(event) {
  console.log("PARENT");
}

function childFunction() {
  if (document.getElementById("check").checked) {
    event.stopPropagation();
  }

  console.log("CHILD");
}
.child {
  padding: 50px;
  width: 100px;
  height: 100px;
  background-color: hotpink;
  text-align: center;
  cursor: pointer;
}

.parent {
  width: 500px;
  height: 500px;
  filter: blur(2px);
  display: flex;
  justify-content: center;
  align-items: center;
  align-content: center;
  background-color: lightgray;
}
<body>
  <div onclick="parentFunction(event)" class="parent">
    <div onclick="childFunction()" class="child">
      Child
    </div>
  </div>
</body>

Stop propagation:
<input type="checkbox" id="check">

相关问题