0

当有人在框外单击时,如何隐藏<div>框。我找不到问题。所以请帮我解决这个问题。

<html>
  <head>
    <title>Test jQuery</title>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $('#button-upload').click(function() {
            $('#id_menu_profile').show();
            });
        });
        var $box = $('#id_menu_profile');
        $(document.body).click(function(){
            if (!$box.has(this).length) { // if the click was not within $box
                $box.hide();
            }
        });
    </script>
</head>
<body>
    <dl>
        <dt><a id="button-upload" href="#">Profile<img src="menu.png" name="arrow_profile"></a></dt>
        <!-- Submenu -->
        <div  id="id_menu_profile" style=" display: none;">
            <dt><a href="index.html">Your Id</a></dt>
            <dt><a href="index.html">Account Setting</a></dt>
            <dt><a href="index.html">Change Password</a></dt>
        </div>
    </dl>
</body>
</html>
4

2 回答 2

1

这应该这样做:

var openDiv;

function toggleDiv(divID) {
    $("#" + divID).fadeToggle(200, function() {
        openDiv = $(this).is(':visible') ? divID : null;
    });
}

$(document).click(function(e) {
    if (!$(e.target).closest('#'+openDiv).length) {
        toggleDiv(openDiv);
    }
});

示例:http: //jsfiddle.net/CHP5w/161/

于 2012-09-30T20:23:12.893 回答
0

您只需要stopPropagation()在框上单击,因此事件不会到达Document单击处理程序,如下所示:

var $box = $('#id_menu_profile');
$(document.body).click(function(){
    // click outside $box
        $box.hide();
});

$box.click(function(e){
    e.stopPropagation(); //Don't let the box click bubble up to Document
    // click within $box
});
于 2012-09-30T20:30:27.110 回答