jQuery绑定点击* ANYTHING * but * ELEMENT * [英] jQuery bind click *ANYTHING* but *ELEMENT*

查看:158
本文介绍了jQuery绑定点击* ANYTHING * but * ELEMENT *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一些元素浮动,当我点击ANYTHING(div,body,无论什么...)但是指定的一个元素(例如div#special)时,我想做一些。

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

我想知道如果有一个更好的方法来实现这个除了以下方法我可以想到...

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


推荐答案

/ em>当 元素被点击的情况下,一般的方法是在文档它处理do this情况,然后向except this元素添加另一个事件处理程序,这简单地防止点击事件冒泡到文档;

To handle the "do this except when this element is clicked" situation, the general approach is to add an event handler to the document which 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;

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

请参阅 event.stopPropagation()文档。对于那些使用早于jQuery 1.7的版本(就像这个问题被提出的情况),你将不能使用 on();而是简单地替换 on() 的两种用法, bind() ;在这种情况下的签名是相同的。

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.

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

这篇关于jQuery绑定点击* ANYTHING * but * ELEMENT *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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