[英]Capturing clicks outside DOM element
I want to capture clicks outside an HTML tag. 我想捕获HTML标记之外的点击。 For example I have this HTML: 例如,我有这个HTML:
<body>
<div>
<ul>
<li id="button">
</li>
</ul>
</div>
</body>
The #button is a smallest square in the middle of the page. #button是页面中间的最小正方形。 Once user clicks outside it something happens, click inside and nothing should happen. 一旦用户在其外部单击,便会发生某种情况,请在内部单击,并且什么也不会发生。
This JS doesn't work because of event propagation: 由于事件传播,此JS不起作用:
jQuery('*').not('li#button').click(...);
so my click event eventually fires on ul, div and body triggering the event. 因此,我的点击事件最终会在触发事件的ul,div和body上触发。 I can't use this: 我不能使用这个:
jQuery('*').click(function(e) {
e.stopPropagation();
if(e.(...)) {}
})
because other events on the page stop working. 因为页面上的其他事件停止工作。
What's the other way of achieving this? 实现此目标的另一种方式是什么?
$(document).bind('click', function(e) {
if($(e.target).closest('#button').length == 0) {
// yourlogic
}
});
Also check How to detect a click outside an element? 还要检查如何检测元素外部的点击?
$(document).click(function(e){
e.stopPropagation();
if($(e.Target).attr(id) != "button"){
// Your logic
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.