我希望父元素在单击时消失
但是我也希望所有子元素都停止实现此功能,因为单击它时父元素隐藏
我想要香草javascript中的解决方案
var listmenu = document.querySelector(".list-overlay");// this list menu nested in overlay element but when click on it also parent element hide but i want no action when click on it
overlay.addEventListener("click",hide);
function hide(){
overlay.classList.add("hide");
}
答案 0 :(得分:0)
您应该使用stopPropagation
来阻止事件从子元素冒泡到父元素。
我在这里添加了一个示例。
function hideParent() {
document.getElementById('parent').style.display = 'none';
}
function onChildClick1(event) {
event.stopPropagation();
}
document.getElementById('child1').addEventListener('click', onChildClick1);
#parent {
height: 80px;
background: red;
}
#child1 {
height: 30px;
background: blue;
color: white;
}
#child2 {
height: 30px;
background: green;
color: white;
}
<div id="parent" onclick="hideParent()">
THIS IS THE PARENT
<div id="child1">
CHILD: STOP PROPAGATION <!-- will *not* trigger parent and remain visible -->
</div>
<div id="child2">
CHILD: DEFAULT BEHAVIOR <!-- will trigger parent and hide -->
</div>
</div>