假设有一些元素漂浮在周围,当我点击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/
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)
我过去这样做过:
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时才会执行.老实说,可能有更好的方法来做到这一点,但这对我有用.
| 归档时间: |
|
| 查看次数: |
73151 次 |
| 最近记录: |