0

好的,这是我用来单击和打开/关闭 div 的一些 jQuery 代码。它工作得很好,但我希望能够单击页面上的任意位置来关闭它。我阅读了有关 e.stopPropagation 的信息,但我不知道如何在此代码中使用它,或者将它放在哪里。有人可以帮忙吗?谢谢。

<script type="text/javascript">
        $(document).ready(function() {
            $('#test').hide().before('<a href="#" id="toggle-menu" class="menu"><img src="images/menu.png" alt="Menu" /></a>');
            $('a#toggle-menu').click(function(e) {
                e.stopPropagation();
                $('#test').slideToggle(200);
                return false;
            });
        });
        </script>

<div id="test"></div>
4

4 回答 4

7

尝试这个:

$(document).ready(function () {
    $('#test').hide().before('<a href="#" id="toggle-menu" class="menu"><img src="images/menu.png" alt="Menu" /></a>');

    $('a#toggle-menu').click(function (e) {
        e.preventDefault();
        $('#test').slideToggle(200);
    });

    $(document).click(function (e) {
        if ($(e.target).closest('#test').length > 0 || $(e.target).closest('#toggle-menu').length > 0) return;
        $('#test').slideUp(200);
    });
});

小提琴演示

于 2013-07-02T17:11:59.760 回答
1

An other solution without delegating event, this way you call event just when needed:

DEMO

just set attribute tabindex to the div and property CSS outline to 0.

$(function () {
    $('#test').on('blur', function (event) {
        $(this).hide();
    });
});

Using your code, set focus like that:

$('a#toggle-menu').click(function (e) {
    var $test = $('#test');
    $test.slideToggle(200,function(){if($test.is(':visible')) $test.focus();});        
    return false;
});
于 2013-07-02T17:14:12.607 回答
0

如果我理解正确,这有什么问题?

$('body').click( function() {
    $('#test').slideToggle( 200 );
});
于 2013-07-02T17:09:46.763 回答
0

I'm assuming you want clicking on the body to toggle the div only if it's already open.

Just use the following snippet:

$(document).ready(function() {
    $('#test').hide().before('<a href="#" id="toggle-menu" class="menu"><img src="images/menu.png" alt="Menu" /></a>');
    $('a#toggle-menu').click(function(e) {
        e.stopPropagation();
        $('#test').slideToggle(200, function() {);
            if ($(this).is(':visible')) {
                $('body').on('click', function() {
                    $('#test').slideToggle(200);
                }
            }
            else {
                $('body').off('click');
            }
        });
        return false;
    });
});

This way, when the div is clicked, it waits for another click -- either anywhere on the body or on the div again -- to close the div. Once it's closed, only clicking on the div itself will open it again.

于 2013-07-02T17:14:22.863 回答