开发者

jQuery button .show() click anything .hide()

I have a div, and when you click on it, used toggle() and shows and hides a list div underneath the button. I want it so that when you click anywhere on the page (not in that div*) it closes. I realize that this shouldn't work with toggle. Can someone p开发者_运维技巧lease point me in the right direction.

I want to click a button then rather than having to click the button again to close the div I want to be able to click anywhere and it closes.


You can stop the click event from bubbling, like this:

$("#divID, #buttonID").click(function(e) {
  e.stopPropagation();
});
$(document).click(function() {
  $("#divID").hide();
});

Using event.stopPropagation() a click from the "button" (which seems to be another <div>?) or from the div won't bubble up to document, anywhere else will...and when the click gets there, it'll close the <div>. So a click from outside the <div> closes, a click from inside does nothing.


return false is your friend here, it prevents default behavior, otherwise the document click event is fired when clicking the button or the div.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(function () {
        $("button").click(function () { $("div").toggle(); return false; });
        $(document).click(function () { $("div").hide(); });
        $("div").click(function () { return false; });
    });
    </script>
</head>
<body>
    <button>Toggle me!</button>
    <div style="height: 400px; width: 400px; background: red;"></div>
</body>


$("*").not("#specialDiv").click(function() {
     $('#specialDiv').hide();
})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜