MouseEvent.buttons
read-only property indicates which buttons are pressed on the mouse (or other input device) when a mouse event is triggered.
Each button that can be pressed is represented by a given number (see below). If more than one button is pressed, the button values are added together to produce a new number. For example, if the secondary (
2
) and auxilary (
4
) buttons are pressed simultaneously, the value is
6
(即,
2 + 4
).
注意:
Do not confuse this property with the
MouseEvent.button
property. The
MouseEvent.buttons
property indicates the state of buttons pressed during any kind of mouse event, while the
MouseEvent.button
property only guarantees the correct value for mouse events caused by pressing or releasing one or multiple buttons.
var buttonsPressed = instanceOfMouseEvent.buttons
A number representing one or more buttons. For more than one button pressed simultaneously, the values are combined (e.g.,
3
is primary + secondary).
0
: No button or un-initialized
1
: Primary button (usually the left button)
2
: Secondary button (usually the right button)
4
: Auxiliary button (usually the mouse wheel button or middle button)
8
: 4th button (typically the "Browser Back" button)
16
: 5th button (typically the "Browser Forward" button)
This example logs the
buttons
property when you trigger a
mousedown
事件。
<p>Click anywhere with one or more mouse buttons.</p> <pre id="log">buttons: </pre>
let log = document.createTextNode('?'); // let log = new Text('?');
function logButtons(e) {
log.data = `${e.buttons} (${e.type})`; // log.nodeValue= `${e.buttons} (${e.type})`;
}
document.addEventListener('mouseup', logButtons);
document.addEventListener('mousedown', logButtons);
// document.addEventListener('mousemove', logButtons);
document.querySelector('#log').appendChild(log)
| 规范 | 状态 | 注释 |
|---|---|---|
|
DOM (文档对象模型) 3 级事件规范
The definition of 'MouseEvent.buttons' in that specification. |
过时 | 初始定义 |
|
UI Events
The definition of 'MouseEvent.buttons' in that specification. |
工作草案 | Current working draft |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
buttons
|
Chrome 43 | Edge 12 |
Firefox
Yes
|
IE 9 | Opera Yes | Safari 11.1 | WebView Android No | Chrome Android No | Firefox Android Yes | Opera Android Yes | Safari iOS 11.3 | Samsung Internet Android No |
完整支持
不支持
见实现注意事项。
Firefox supports the
buttons
attribute on Windows, Linux (GTK), and macOS with the following restrictions:
mouseup
event always includes the releasing button information in the
buttons
值。
buttons
attribute always returns
0
because there is no platform API for implementing this feature.
MouseEvent