jQuery 绑定(bind)点击 *任何东西* 但 *元素*

标签 jquery click

假设有一些元素漂浮在周围,当我点击任何东西(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
});

最佳答案

要处理“在单击this 元素时执行此操作except”的情况,一般方法是向document 处理“do this”情况,然后向“except this”元素添加另一个事件处理程序,这只是防止点击事件冒泡到 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.
});

参见 the event.stopPropagation() documentation .对于那些使用早于 jQuery 1.7 版本的人(就像问这个问题时的情况),您将无法使用 on();而不是简单地替换 on() 的 2 次使用与 bind() ;本例中的签名是相同的。

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

关于jQuery 绑定(bind)点击 *任何东西* 但 *元素*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6635659/

相关文章:

JavaScript 嵌套 for 循环向对象添加值

javascript - 跨浏览器的 JavaScript

javascript - Jquery li点击事件没有触发

javascript - 删除 onclick 函数

flash - Actionscript 3.0 一次拖动一个 MovieClip

java - Web 应用程序的屏幕捕获

jquery - 页面中的透明图像

javascript - JQuery 模板不适用于数组

Jquery:检测是否单击了鼠标中键或右键,如果是,请执行以下操作:

在 C 中按下特定键时单击鼠标