jQuery绑定点击*ANYTHING*但*ELEMENT*

rai*_*One 68 jquery click

假设有一些元素漂浮在周围,当我点击ANYTHING(divs,body,等等......)但是指定的那个(例如div#special)时,我正试图做一些.

我想知道是否有更好的方法来实现这一点,除了我能想到的以下方法......

$(document).bind('click', function(e) {
    get mouse position x, y
    get the element (div#special in this case) position x, y
    get the element width and height
    determine if the mouse is inside the element
    if(inside)
        do nothing
    else
        do something
});
Run Code Online (Sandbox Code Playgroud)

Mat*_*att 114

要处理" 除了单击元素时执行此操作"的情况,一般方法是向document处理"执行此操作"的情况添加事件处理程序,然后将另一个事件处理程序添加到"除此"元素之外,这只是防止点击事件冒泡到document;

$('#special').on('click', function(e) {
    e.stopPropagation();
});

$(document).on('click', function (e) {
 // Do whatever you want; the event that'd fire if the "special" element has been clicked on has been cancelled.
});
Run Code Online (Sandbox Code Playgroud)

请参阅event.stopPropagation()文档.对于那些使用早于jQuery 1.7版本的人(就像问这个问题的情况一样),你将无法使用on(); 代替简单的替换2种的用途on()bind(); 在这种情况下签名是相同的.

在这里演示; http://jsfiddle.net/HBbVC/

  • 没有冒犯,但这与我链接到的副本中给出的答案基本相同:http://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element (6认同)
  • @Felix:我现在可以看到,但是当我开始写回复时你没有发表评论:(. (4认同)

bma*_*ity 43

你也可以这样做

$(document).bind('click', function(e) {
  if(!$(e.target).is('#special')) {
    // do something
  }
});
Run Code Online (Sandbox Code Playgroud)

或者如果div#special具有您可以执行的子元素

$(document).bind('click', function(e) {
  if($(e.target).closest('#special').length === 0) {
    // do something
  }
});
Run Code Online (Sandbox Code Playgroud)


Dan*_*ith 5

我过去这样做过:

jQuery("body").bind("click", function(e)
{
    var obj = (e.target ? e.target : e.srcElement);
    if (obj.tagName != 'div' && obj.id != 'special')
    {
        // Perform your click action. 
        return false;
    }
});
Run Code Online (Sandbox Code Playgroud)

只有在你没有点击div#special时才会执行.老实说,可能有更好的方法来做到这一点,但这对我有用.

  • 你不需要测试`e.target`.它将永远存在,jQuery规范化事件对象.如果`div#special`包含其他元素,它将无法工作. (2认同)