http://jsfiddle.net/dgjJe/1/

In the above jsfiddle I am trying to capture when the user clicks outside of the .inner div but I can't seem to get it working.

HTML:

<div class="outer">
    <div class="inner"></div>
</div>

Javascript:

$(document).mousedown(function (e) {
    var div = $(".inner");
    if (div.has(e.target).length === 0) {
        alert('clicked outside of .inner');
    }
});

CSS:

.outer { width:200px; height:200px; border:1px solid #000; position:relative; }
.inner { width:100px; height:100px; border:1px solid #000; position:absolute; top:25px; left:25px; }
有帮助吗?

解决方案

div variable in your code refers to the .inner element, so it doesn't have .inner child element. Based on the structure of markup, has method is not useful here. You can use is method:

$(document).mousedown(function(e) {
    if ( !$(e.target).is('.inner') ) {
        alert('clicked outside of .inner');
    }
});

http://jsfiddle.net/MJmPF/

The above method doesn't work if the .inner has children elements, for this case you can use closest method:

$(document).mousedown(function(e) {
    if ( !$(e.target).closest('.inner').length ) {
        alert('clicked outside of .inner');
    }
});

http://jsfiddle.net/wHpa8/

其他提示

You can use jQuery's $.on() / $.bind() (depending on your jQuery version) to listen for the mousedown event on the outer div while preventing the inner div from reacting to the mousedown event using event.stopPropagation() like so:

$('.inner').on('mousedown', function(e){
    e.stopPropagation()
});
$('.outer').on('mousedown', function(){
    alert('outer');
    return false;
});

Update Fiddle Here

I hope this helps!

$(document).mousedown(function (e) {
    var div = $(".inner");
    if (!$(e.target).is('.inner') && div.has(e.target).length === 0) {
        console.log('clicked outside of .inner');
    }
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top