检测元素外的点击? [英] Detect click outside element?

查看:25
本文介绍了检测元素外的点击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似于这个问题,但将其视为更进一步.我想检测一组项目之外的点击,我正在通过以下方式处理:

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:

  • 单击菜单项可将其打开.
  • 单击相同的菜单项(或其子菜单项)可将其关闭.
  • 点击另一个菜单项关闭第一个,打开第二个.
  • 点击(打开)菜单项将关闭它们.

我尝试了以下代替上面的 $('body').one() 命令来忽略对菜单项的点击,但收效甚微:

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!

推荐答案

只需将主体点击处理程序移到外面并执行以下操作:

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
    }
});

评论中错误地指出e.target在IE中不起作用;这不是真的,因为 jQuery 的 Event 对象 在必要时修复了这些不一致(IE, Safari).

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).

这篇关于检测元素外的点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆