如何使用jQuery检测文档中任何位置的左键单击? [英] How to detect left click anywhere on the document using jQuery?

查看:125
本文介绍了如何使用jQuery检测文档中任何位置的左键单击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在有这个:

$(document).click(function(e) { alert('clicked'); });

在Firefox中,当我左键单击或右键单击时,此事件将触发。我只想在左键单击时触发它。

In Firefox, this event is firing when I left-click OR right-click. I only want it to fire when I left-click.

将单击处理程序附加到文档的工作方式与将其附加到其他元素的工作方式不同吗?对于其他元素,它似乎只会触发左键点击。

Does attaching a click handler to the document work differently than attaching it to other elements? For other elements, it only seems to fire on left clicks.

除了查看e.button之外,还有办法检测左键点击,这是依赖于浏览器的吗?

Is there a way to detect only left clicks besides looking at e.button, which is browser-dependent?

谢谢

推荐答案

试试

$(document).click(function(e) { 
    // Check for left button
    if (e.button == 0) {
        alert('clicked'); 
    }
});

然而,对于IE是否在左键单击时返回1或0似乎存在一些混淆,可能需要对此进行测试:)

However, there seems to be some confusion as to whether IE returns 1 or 0 as left click, you may need to test this :)

在此处进一步阅读: jQuery Gotcha

编辑:错过了你问的位置不要使用 e.button 。抱歉!

EDIT: missed the bit where you asked not to use e.button. Sorry!

但是,示例此处无论在FF或IE中查看它都会返回相同的ID,并使用e.button。可能已经更新了jQuery框架?另一个答案是IE的旧版本返回不同的值,这将是一个痛苦。不幸的是我在这里只有IE 7/8进行测试。

However, the example here returns the same ID regardless of looking at it in FF or IE, and uses e.button. could possibly have updated the jQuery framework? The other answer is that older versions of IE return a different value, which would be a pain. Unfortunately I only have IE 7/8 here to test against.

这篇关于如何使用jQuery检测文档中任何位置的左键单击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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