简体   繁体   中英

Don't trigger main container click if clicking in specific child element

I have a click listener attached to my #main container

main.addEventListener("click", function() {
    console.log("clicked main");
});

Within my main container I have an #element also with a click listener

element.addEventListener("click", function() {
    console.log("clicked element but dont trigger main click");
});

How do I avoid triggering the #main click when clicking within #element ?

Fiddle: http://jsfiddle.net/gufo7mmc/1/

Use event.stopPropagation()

element.addEventListener("click", function() {
    console.log("clicked element but dont trigger main click");
    event.stopPropagation();
});

 var main = document.getElementById("main"); var element = document.getElementById("element"); var textElement = document.getElementById("text"); main.addEventListener("click", function() { console.log("clicked main"); }); main.addEventListener("mouseenter", function() { textElement.style.visibility = "visible"; console.log("trigger on everything except #element"); }); main.addEventListener("mouseleave", function() { textElement.style.visibility = "hidden"; }); element.addEventListener("click", function() { console.log("clicked element but dont trigger main click"); event.stopPropagation(); }); 
 #main { position: absolute; width: 300px; height: 600px; background-color: red; } #element { position: absolute; width: 100%; height: 100px; background-color: green; } #text { position: absolute; width: 100px; height: 100px; top: 200px; background-color: blue; visibility: hidden; } 
 <div id="main"> <div id="element"></div> <div id="text">HELLO</div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM