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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6635659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:09:43  来源:igfitidea点击:

jQuery bind click *ANYTHING* but *ELEMENT*

jqueryclick

提问by railOne

Say there are some elements floating around, and I'm trying to do some when I click ANYTHING(divs, body, whatever...) but the one specified (e.g. div#special).

假设有一些元素在浮动,当我点击任何东西(divs,body,whatever...)但指定的那个(例如div#special)时,我试图做一些。

I'm wondering if there's a better way to achieve this besides the following method I can think of...

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

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

回答by Matt

To handle the "do this exceptwhen thiselement is clicked" situation, the general approach is to add an event handler to the documentwhich handles the "do this" case, then add another event handler to the "except this" element, which simply prevents the click event bubbling up to the document;

要处理“除此元素被点击执行此操作”的情况,一般的做法是在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.
});

See the event.stopPropagation()documentation. For those of you using versions earlier than jQuery 1.7 (as was the case when this question was asked), you won't be able to use on(); instead simple replace the 2 uses of on()with bind(); the signature in this case is the same.

请参阅event.stopPropagation()文档。对于那些使用早于 jQuery 1.7 的版本的人(问这个问题时就是这种情况),您将无法使用on(); 取而代之的是简单地替换on()with的 2 种用法bind();这种情况下的签名是相同的。

Demo here; http://jsfiddle.net/HBbVC/

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

回答by bmavity

You could also do

你也可以这样做

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

or if div#special has child elements you could do

或者如果 div#special 有你可以做的子元素

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

回答by Dan Smith

I've done it like this in the past:

我过去这样做过:

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

This would only execute if you didn't click on div#special. Honestly there may be better ways to do it, but this has worked for me.

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

回答by El'

you need to do different binds, there is no need to process all this clicks in one function

你需要做不同的绑定,没有必要在一个函数中处理所有这些点击

$('body').bind('click', function(e){
  bodyClickEvent();
});
$('div.floating').bind('click',function(e){
  elementClickEvent(this);
  e.stopPropagation(); //prevents bodyClickEvent
});
  $('div#special').bind('click', function(){
  e.stopPropagation(); //prevents bodyClickEvent
});

回答by Owen

I wrote this today for an issue i was having as i don't like having click events bound to the document the whole time, so for my scenario this works, using callbacks from functions.

我今天写这篇文章是为了解决我遇到的一个问题,因为我不喜欢一直将点击事件绑定到文档,所以对于我的场景,使用函数的回调是有效的。

$('#button').click(function(){
        //when the notification icon is clicked open the menu
        $('#menu').slideToggle('slow', function(){
            //then bind the close event to html so it closes when you mouse off it.
            $('html').bind('click', function(e){
                $('#menu').slideToggle('slow', function(){
                    //once html has been clicked and the menu has closed, unbind the html click so nothing else has to lag up
                    $('html').unbind('click');
                });
            });
            $('#menu').bind('click', function(e){
                //as when we click inside the menu it bubbles up and closes the menu when it hits html we have to stop the propagation while its open
                e.stopPropagation();
                //once propagation has been successful! and not letting the menu open/close we can unbind this as we dont need it!
                $('#menu').unbind('click');
            });
        });
    });

回答by john Smith

I once solved this a little easier than the other answers, whithout taking care that click really goes down the DOM-Tree

我曾经比其他答案更容易解决这个问题,而无需注意点击确实会沿着 DOM-Tree

just check if your element is hovered ;)

只需检查您的元素是否悬停;)

$(document).on('click', function (e) {

  if($('#special:hover').length > 0){
    // on our special element
  }else{
    // not on our special element
  }

});

Cheers

干杯