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

推荐答案

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

the event.stopPropagation() documentation.对于那些使用jQuery1.7之前版本的用户(当被问到这个问题时就是这样),您将无法使用on();用bind()代替on()的2个用途;这种情况下的签名是相同的.

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

Jquery相关问答推荐

使用jquery将外部代码插入div

JQuery - 从先前 Select 的下拉列表中隐藏/显示选项

如何在外部JS文件中使用带有参数的laravel路由

$ 不是函数 - jQuery 错误

jQueryUI 模态对话框不显示关闭按钮 (x)

通过 .push() 方法向对象添加项目

在 contenteditable div 中的插入符号处插入 html

javascript:检测滚动结束

在单击事件上判断 Ctrl / Shift / Alt 键

谷歌图表重绘/zoom 窗口调整大小

如何在实际图像下载时显示加载图像

使用 jQuery 获取选定的选项 id

使用 jQuery 拖放防止单击事件

如何通过 DOM 容器访问 Highcharts 图表?

jQuery 如果 div 包含此文本,则替换该部分文本

Select jQuery UI 自动完成后清除表单字段

jquery - 从一个非常大的表中删除所有行的最快方法

为什么要定义一个匿名函数并将 jQuery 作为参数传递给它?

jQuery clone() 不克隆事件绑定,即使使用 on()

在 Javascript/jQuery 中,(e) 是什么意思?