2012-04-03 61 views
1

让我们说我有哪个鼠标按钮在javascript中点击了onmouseup?

<div onmouseup="myfunction()"> 
    </div> 

但我怎么会知道,如果被点击鼠标左右键?

+2

有你搜寻它的第一? – wong2 2012-04-03 17:34:07

+0

尝试寻找到'event.which'财产 – antyrat 2012-04-03 17:35:56

+0

http://stackoverflow.com/questions/1206203/how-to-distinguish-between-left-and-right-mouse-click-with-jquery – 2012-04-03 17:36:36

回答

-1
function doSomething(e) { 
    var rightclick; 
    if (!e) var e = window.event; 
    if (e.which) rightclick = (e.which == 3); 
    else if (e.button) rightclick = (e.button == 2); 
    alert('Rightclick: ' + rightclick); // true or false 
} 
+0

可能[缺少来源](http://stackoverflow.com/a/8678019/908879) – ajax333221 2012-04-03 17:59:11

+0

好的选择...你需要检查我的答案在这里... http: //stackoverflow.com/questions/9953651/window-event-doesnt-work-in-firefox/9953733#9953733 – Dasarp 2012-04-03 18:02:15

+0

我联系的职位是年纪比你 – ajax333221 2012-04-03 18:04:51

3

有用于找出已被点击哪一个鼠标按键两个属性:whichbutton。请注意,这些属性并不总是适用于点击事件。要安全地检测鼠标按钮,您必须使用mousedown或mouseup事件。

which是一个古老的Netscape属性。这将为鼠标按钮提供以下值。

Left button - 1 
Middle button - 2 
Right Button - 3 

没有问题,除了它微不足道的支持(以及它也用于密钥检测的事实)。

现在按钮已被超过所有承认被玷污。根据W3C其值应为:

Left button – 0 
Middle button – 1 
Right button – 2 

根据微软自己的价值观应该是:

Left button – 1 
Middle button – 4 
Right button – 2 

毫无疑问,微软模式比W3C的更好。 0应该表示“没有按钮被按下”,其他任何事情都是不合逻辑的。

此外,只有在微软模式按钮值可以结合起来,使5,将意味着“左边和中间的按钮”。甚至连浏览器6都没有支持这一点,但在W3C模型中,这样的组合在理论上是不可能的:你永远不知道左边的按钮是否也被点击了。

和检查按钮的类型被点击其中始终使用特征检测为whichbutton性质

if (e.which) { 
    // old netsapce implementation 
    consoel.log((e.which == 3) + ' right click'); 
} else if (e.button) { 
    // for microsoft or W3C model implementation 
    consoel.log((e.button == 2) + ' right click'); 
} 

参考:

http://www.quirksmode.org/js/events_properties.html

0

经过这样的功能:

function getEvt (evt) { 
    var mouseEvt = (evt).which; 
    var mMouseEvt = evt.button; 
    console.log(mouseEvt); 
    console.log(mMouseEvt); 
} 

它返回int。例如,对于左击:

1  listeners.js (line 43) 
0  listeners.js (line 44) 
相关问题