检测点击外部元素?

时间:2009-07-21 18:26:51

标签: javascript jquery dom

this question类似,但更进了一步。我想检测一组项目之外的点击,我按以下方式处理:

$('#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();
    });
});

不幸的是,当另一个菜单项打开时,这就像魅力一样 单击第二个,它需要两次单击才能打开第二个项目。首先 单击隐藏已打开的第一个菜单项,第二个菜单显示第二个菜单 项目

“正确”行为以下列方式起作用:

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

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

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

一如既往,感谢您的帮助!

2 个答案:

答案 0 :(得分:29)

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

$('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's Event object在必要时修复了这些不一致(IE,Safari)。

答案 1 :(得分:15)

我很久以前写过这篇文章,在jQuery的辉煌岁月之前......

function clickedOutsideElement(elemId) {
  var theElem = getEventTarget(window.event);
  while(theElem != null) {
    if(theElem.id == elemId)
      return false;
    theElem = theElem.offsetParent;
  }
  return true;
}

function getEventTarget(evt) {
  var targ = (evt.target) ? evt.target : evt.srcElement;
  if(targ != null) {
    if(targ.nodeType == 3)
      targ = targ.parentNode;
  }
  return targ;
}

document.onclick = function() {
  if(clickedOutsideElement('divTest'))
    alert('Outside the element!');
  else
    alert('Inside the element!');
}
相关问题