我有嵌套的div元素。外面应该有移动和单击的事件。我想使嵌套元素充当按钮,并防止事件从外部起作用。在示例中,当我们单击红色部分时,两个事件都在发生。当我们单击红色部分时,如何从绿色部分停止事件? stopPropagation()没有完成这项工作。我正在使用React,而且我的结构比示例中的还要复杂。但是出于清楚的原因,我想减少。
如果有人可以帮助,我会很高兴。
#bigCircle {
display: flex;
justify-content: center;
align-items: center;
width: 180px;
height: 180px;
border-radius: 50%;
background-color: green;
}
#smallCircle {
width: 40px;
height: 40px;
border-radius: 50%;
background-color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div id="bigCircle">
<div id="smallCircle"></div>
</div>
<script>
document.getElementById("bigCircle").addEventListener("click",myBigCircle);
document.getElementById("smallCircle").addEventListener("click",mySmallCircle);
function myBigCircle(){
console.log("Hello");}
function mySmallCircle(){
console.log("Bye");}
</script>
</body>
</html>
使用event.stopPropagation()
防止父级触发。
#bigCircle {
display: flex;
justify-content: center;
align-items: center;
width: 180px;
height: 180px;
border-radius: 50%;
background-color: green;
}
#smallCircle {
width: 40px;
height: 40px;
border-radius: 50%;
background-color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div id="bigCircle">
<div id="smallCircle"></div>
</div>
<script>
document.getElementById("bigCircle").addEventListener("click",myBigCircle);
document.getElementById("smallCircle").addEventListener("click",mySmallCircle);
function myBigCircle(){
console.log("Hello");}
function mySmallCircle(event){
event.stopPropagation()
console.log("Bye");
}
</script>
</body>
</html>