鼠标事件中button和which的区别

cho*_*per 6 javascript jquery

event.buttonJavascript 鼠标事件和之间有什么区别event.which

Min*_*hev 5

事件按钮

指示哪个鼠标按钮导致了该事件。

事件.which

根据 jQuery 的文档:

...event.which 还规范了按钮按下(mousedown 和 mouseupevents),报告左按钮为 1,中按钮为 2,右按钮为 3。使用 event.which 而不是 event.button。

不同之处

在所有现代浏览器(IE8+)中event.button将为您提供以下值:

0   Specifies the left mouse-button
1   Specifies the middle mouse-button
2   Specifies the right mouse-button
Run Code Online (Sandbox Code Playgroud)

在 IE8 及更早版本中:

1   Specifies the left mouse-button
4   Specifies the middle mouse-button
2   Specifies the right mouse-button
Run Code Online (Sandbox Code Playgroud)

event.which通过为您提供以下值来标准化这些结果:

1   Specifies the left mouse-button
2   Specifies the middle mouse-button
3   Specifies the right mouse-button
Run Code Online (Sandbox Code Playgroud)


eve*_*ack 5

尽管我投了赞成票,但我对最后一个解决方案还是比较害羞。根据 MDN 文档:

This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future

所以,MouseEvent.button仍然是首选。一个有趣的(案例)替代方案可能是MouseEvent.buttons,它允许您确定触发事件时按下的所有按钮。