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

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

问题描述

类似于此问题,但将其进一步。我想检测一组项目之外的点击,我以下列方式处理:

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() / code>命令忽略菜单项的点击没有什么成功:

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不正确的注释中,e.target不正确地指出,这不是真的,因为 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天全站免登陆