Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

javascript - Detect click outside element?

Similar to this question, but taking it a step further. I would like to detect clicks outside of a set of items, which I am handling in the following way:

$('#menu div').live('click', function() {
    // Close other open menu items, if any.
    // Toggle the clicked menu item.

    $('body').one('click', function(event) {
        // Hide the menu item.
        event.stopPropagation();
    });
});

This works like a charm, unfortunately, when another menu item is open and a second is clicked, it requires two clicks to open the second item. The first click hides the first menu item that was open, the second shows the second menu item.

The "correct" behavior works in the following way:

  • Clicking a menu item opens it.
  • Clicking the same menu item (or it's children) closes it.
  • Clicking another menu item closes the first, opens the second.
  • Clicking away from (open) menu items closes them.

I have tried the following in place of the above $('body').one() order to ignore clicks on menu items with little success:

// Captures click on menu items in spite of the not.
$('*').not('#menu *').one('click', function() { // Hide menu }
$('*:not(#menu)').one('click', function() { // Hide menu }

As always, thanks for any help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just move the body click handler outside and do something like this:

$('body').bind('click', function(e) {
    if($(e.target).closest('#menu').length == 0) {
        // click happened outside of menu, hide any visible menu items
    }
});

It was incorrectly pointed out in the comments that e.target does not work in IE; this is not true as jQuery's Event object fixes these inconsistencies where necessary (IE, Safari).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...