简体   繁体   English

鼠标单击父元素,但防止其子元素触发事件

[英]javascript - Mouse Click on parent element , but prevent it's child element to fire event

How to define on child element, not to trigger an event, like on .mouseclick = 'no-event' or : .mousedown = 'no-event' with natural Javascript command? 如何使用自然Javascript命令在子元素上定义而不触发事件,例如.mouseclick = 'no-event'或: .mousedown = 'no-event'

So, it's parent will get the the first event before bubbling-up, the parent element event will get e. 因此,它的父级事件将在冒泡之前获得第一个事件,父级元素事件将得到e。 target = e.currentTarget

I need to do it on some specific child elements, and some not. 我需要对某些特定的子元素执行此操作,而对某些子元素则不需要。

On parent element the 'capture', does not give the correct behaviour as mentioned above. 在父元素上,“捕获”没有给出如上所述的正确行为。

All other solutions I follow on the web, are giving many 'tricky' solutions that don't work correctly. 我在网络上遵循的所有其他解决方案都提供了许多无法正常工作的“棘手”解决方案。

var parentEl = document.getElementById('parent');
var childEl = document.getElementById('child');

parentEl.addEventListener('click', function(event) {

}, true)
childEl.addEventListener('click', function(event) {

}, true)

If you pass the true on eventListener it stops the event from bubbling.

You could give the children a custom class which determines it should be clickable or not. 您可以给孩子们一个自定义类,该类确定它是否应单击。 Inside the callback function for it's parent container check which class the target is using and act accordingly. 在其父容器的回调函数中,检查目标正在使用哪个类并采取相应的措施。

Here's an example: 这是一个例子:

 document.getElementById("container").addEventListener('click', function(e) { if (e.target.className == "clickable") { console.log("I should do something!"); } else { console.log("I should NOT do something!"); } }); 
 <div id="container"> <div class="clickable"> this is clickable </div> <div> this is not clickable </div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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