如何防止父对象激活子对象的事件



这是代码。您应该在不退出蓝色div或输入红色div的情况下从左方块转到右方块。问题是,红色div和它的子项,即右侧方块都有相同的事件侦听器,但其中一个以失败告终,另一个以胜利告终。有没有办法在不重做所有内容的情况下解决这个问题?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
html {
text-align: center;
}
.outer {
width: 500px;
height: 500px;
border-style: solid;
border-color: black;
border-width: 1px;
position: absolute;
left: 36%;
right: 50%;
margin-top: 100px;
background-color: lightskyblue;
}
.mid {
width: 440px;
height: 440px;
border-style: solid;
border-color: black;
border-width: 1px;
margin-left: 30px;
margin-top: 30px;
margin-right: 30px;
margin-bottom: 30px;
background-color: #ffbcbc;
}
.inner {
width: 100px;
height: 100px;
border-style: solid;
border-color: black;
border-width: 1px;
display: inline-block;
margin-top: 170px;
background-color: rgb(134, 255, 134);
}
#in1 {
float: left;
border-left: none;
}
#in2 {
float: right;
border-right: none;
}
</style>
</head>
<body>
<div class="outer" id="outer">
<div class="mid" id="mid">
<div class="inner" id="in1">
</div>
<div class="inner" id="in2">
</div>
</div>
</div>
<script>
let out = document.getElementById("outer")
let mid = document.getElementById("mid")
let in1 = document.getElementById("in1")
let in2 = document.getElementById("in2")
in1.addEventListener("mouseover", GameStart)
function GameOver() {
alert("Pokušajte ponovno")
out.removeEventListener("mouseleave", GameOver)
mid.removeEventListener("mouseenter", GameOver)
in2.removeEventListener("mouseenter", GameWon)
return
}
function GameWon() {
alert("Pobijedili ste")
out.removeEventListener("mouseleave", GameOver)
mid.removeEventListener("mouseenter", GameOver)
in2.removeEventListener("mouseenter", GameWon)
return
}
function GameStart() {
in1.addEventListener("mouseleave", Game)
}
function Game() {
in1.removeEventListener("mouseleave", Game)
out.addEventListener("mouseleave", GameOver)
mid.addEventListener("mouseover", GameOver)
in2.addEventListener("mouseenter", GameWon)
}
</script>
</body>
</html>

在这种情况下,您需要执行event capture。并显式地查找触发事件的e.target(单击的元素(,并分别处理该逻辑。

在演示示例中,我模仿了你的游戏示例:试试这个

document.querySelector(".parent").addEventListener("click",(e)=>{
if(e.target.className === "child1"){
console.log("Continue the game")
}
if(e.target.className === "child2"){
console.log("Game Over !!!")
}
})
.child1,.child2{
background:teal;
height:100px;
width:300px;
}
.child1{
margin-bottom:2rem;
}
<div class="parent">
<div class="child1">
</div>
<div class="child2">
</div>
</div>

最新更新