如何在元素之外的任何地方的click事件上隐藏元素? [英] How do I hide an element on a click event anywhere outside of the element?
问题描述
我想知道这是否是单击页面上任何地方时隐藏可见元素的正确方法.
I would like to know whether this is the correct way of hiding visible elements when clicked anywhere on the page.
$(document).click(function (event) {
$('#myDIV:visible').hide();
});
在元素边界内发生点击事件时,元素(div,span等)不应消失.
The element (div, span, etc.) shouldn't disappear when a click event occurs within the boundaries of the element.
推荐答案
如果我理解,您想在除div以外的任何位置单击时隐藏div,并且如果确实在div上方单击时,则不应关闭该div .您可以使用以下代码来做到这一点:
If I understand, you want to hide a div when you click anywhere but the div, and if you do click while over the div, then it should NOT close. You can do that with this code:
$(document).click(function() {
alert("me");
});
$(".myDiv").click(function(e) {
e.stopPropagation(); // This is the preferred method.
return false; // This should not be used unless you do not want
// any click events registering inside the div
});
这会将点击绑定到整个页面,但是如果您点击有问题的div,它将取消点击事件.
This binds the click to the entire page, but if you click on the div in question, it will cancel the click event.
这篇关于如何在元素之外的任何地方的click事件上隐藏元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!