hide div when clicking outside the container with jquery

I want to hide a div when they click out of it. For that I have this code that works perfectly:

var box3=$(".despcnt");
box3.mouseup(function () {
    return false;
});

$(this).mouseup(function (a) {
    if(!($(a.target).parent(".despcnt").length>0)){
        box3.removeClass("dino");box3.hide()
    }
});

But I want to exclude from the class. Despcnt a link that has the class desplcnt so when clicking outside the den or closes that same link ... not tried putting it did not work.

Any idea?

HTML

<a class="desplcnt" href="#">Link</a>
<div class="despcnt">
    <ul>
        <li><a data-value="1" href="#">Title</a></li>
    </ul>
</div>

var $despcnt = $(".despcnt");

/* Hide the popup whereas clicking outside */
$(document).on("click", function() {
  $despcnt.hide();
});

/* Don't hide the popup whereas clicking inside */
$despcnt.on("click", function(evt) {
    evt.stopPropagation();
});

So, when you click on title, you want link to hide. But when you click anywhere else, you want title to hide? If so, you can assign Title a mouseup event, and then hide the link from there, then use e.stopPropagation() in order to bypass the global mouseup attached to window when you used this . Here is a demo: http://jsfiddle.net/pUnvR/1/

Here is the code:

html

<a class="desplcnt" href="#">Link</a>
<div class="despcnt">
 <ul>
    <li><a data-value="1" href="#">Title</a></li>
 </ul>
</div>

js

var box3=$(".despcnt");
box3.mouseup(function (e) {
    $(".desplcnt").hide();
    e.stopPropagation();
});

$(this).mouseup(function (a) {
    if(!($(a.target).parent(".despcnt").length>0)){
        box3.removeClass("dino");
        box3.hide();
    }
});
链接地址: http://www.djcxy.com/p/83648.html

上一篇: 当用户使用jQuery在其外部点击时隐藏DIV

下一篇: 使用jquery在容器外单击时隐藏div