javascript 禁用“div”上的鼠标事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23261853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Disabling mouse events on 'div'
提问by Rethna
I have an interesting problem in disabling mouse events using the 'pointer-events' css styling.
我在使用“指针事件”css 样式禁用鼠标事件时遇到了一个有趣的问题。
Please refer the fiddle. It has a parent and two children div, and I make 'pointer-events' as 'none' to one of the children. If I click on that div, its mouse listeners are not triggered (this is expected) but mouse events of its parent div is triggered.
请参考小提琴。它有一个父级和两个子级 div,我将其中一个子级的“指针事件”设为“无”。如果我单击该 div,则不会触发其鼠标侦听器(这是预期的),但会触发其父 div 的鼠标事件。
$('#parent').click(function(){
console.log("Parent clicked");
});
How to disable mouse events on the parent div, if I clicked on its children which are disabled for mouse events?
如何禁用父 div 上的鼠标事件,如果我点击了对鼠标事件禁用的子级?
One option is to filter using an "if" condition on the parent click. But i don't need it, as I want to listen for mouse events on 'divs' present behind the parent.
一种选择是在父点击上使用“if”条件进行过滤。但我不需要它,因为我想在父级后面的“div”上监听鼠标事件。
Please provide some help :)
请提供一些帮助:)
thanks, Rethna
谢谢,雷思娜
回答by Matheus
I couldnt make the pointer-events work as I intended, so I changed the javascript in order to achieve what you wanted. What i did was to event.stopPropagation on the child2, so you can click him and only fire his click event, not his parent's click event. By the way, i know little about jquery, so I wrote a mixed beetwen pure javascript and jquery, hope someone can help me translate that.
我无法使指针事件按预期工作,因此我更改了 javascript 以实现您想要的。我所做的是在 child2 上进行 event.stopPropagation,所以你可以点击他并且只触发他的点击事件,而不是他父母的点击事件。顺便说一下,我对jquery知之甚少,所以我写了一个混合beetwen纯javascript和jquery,希望有人能帮我翻译一下。
Here comes the fiddle
小提琴来了
CSS:
CSS:
child1{
孩子1{
background-color:#ff0000;
width:100px;
height:100px;
pointer-events: all;
}
}
child2{
孩子2{
background-color:#00ff00;
width:100px;
height:100px;
pointer-events: all;
}
}
parent{
父母{
pointer-events: none;
}
}
Javascript:
Javascript:
$(document).ready(function(){
document.getElementById('child1').addEventListener('click', function(){
console.log("child1 clicked");
}, false);
document.getElementById('child2').addEventListener('click', function(e){
e.stopImmediatePropagation();
console.log("child2 clicked");
}, false);
document.getElementById('parent').addEventListener('click', function(){
console.log("Parent clicked");
}, false);
});