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