I'm using the following code to animate a block. In my code, div_animate()
essentially hides a <div>
with the specified selector if it is currently visible.
$(document).click(function(event开发者_开发技巧){
div_animate("#container");
});
I need to determine whether the user clicked on a child of #container
and if so, return false;
-- as far as I can tell, the code for this would look something like this:
$(document).click(function(event){
if ( /* the event's target has a parent of #container */ ) {
return false;
} else {
div_animate("#container");
}
});
Any thoughts?
The simplest thing would be:
if ($(event.target).is('#container *, #container')) // edited - thanks @gnarf
// is a child
else
// is not a child
There are different choices you could make for detecting whether it's a child of the target (or non-target) container; that's just one. An alternative:
if ($(event.target).closest('#container').length)
You can prevent the action if the click originated on or in #container
, like this:
$(document).click(function(event){
var c = $("#container")[0];
if (event.target == c || $.contains(c, event.target)) {
return false;
} else {
div_animate("#container");
}
});
The first check is if it came from #container
itself, the second is if it came from a child, that #container
$.contains()
. A completely alternative, simpler way is to just prevent the bubble up to document
when clicking on #container
, like this:
$("#container").click(function(e) {
e.stopPropagation();
});
$(document).click(function() {
div_animate("#container");
});
精彩评论