MouseEvent.button
read-only property indicates which button was pressed on the mouse to trigger the event.
This property only guarantees to indicate which buttons are pressed during events caused by pressing or releasing one or multiple buttons. As such, it is not reliable for events such as
mouseenter
,
mouseleave
,
mouseover
,
mouseout
or
mousemove
.
Users may change the configuration of buttons on their pointing device so that if an event's button property is zero, it may not have been caused by the button that is physically left–most on the pointing device; however, it should behave as if the left button was clicked in the standard button layout.
注意:
Do not confuse this property with the
MouseEvent.buttons
property, which indicates which buttons are pressed for all mouse events types.
var buttonPressed = instanceOfMouseEvent.button
A number representing a given button:
0
: Main button pressed, usually the left button or the un-initialized state
1
: Auxiliary button pressed, usually the wheel button or the middle button (if present)
2
: Secondary button pressed, usually the right button
3
: Fourth button, typically the
Browser Back
button
4
: Fifth button, typically the
Browser Forward
button
As noted above, buttons may be configured differently to the standard "left to right" layout. A mouse configured for left-handed use may have the button actions reversed. Some pointing devices only have one button and use keyboard or other input mechanisms to indicate main, secondary, auxilary, etc. Others may have many buttons mapped to different functions and button values.
<button id="button" oncontextmenu="event.preventDefault();">Click here with your mouse...</button> <p id="log"></p>
let button = document.querySelector('#button');
let log = document.querySelector('#log');
button.addEventListener('mouseup', logMouseButton);
function logMouseButton(e) {
if (typeof e === 'object') {
switch (e.button) {
case 0:
log.textContent = 'Left button clicked.';
break;
case 1:
log.textContent = 'Middle button clicked.';
break;
case 2:
log.textContent = 'Right button clicked.';
break;
默认:
log.textContent = `Unknown button code: ${e.button}`;
}
}
}
| 规范 | 状态 | 注释 |
|---|---|---|
|
DOM (文档对象模型) 3 级事件规范
The definition of 'MouseEvent.button' in that specification. |
过时 | Compared to DOM (文档对象模型) 2 级事件规范 , the return value can be negative. |
|
DOM (文档对象模型) 2 级事件规范
The definition of 'MouseEvent.button' in that specification. |
过时 | 初始定义。 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
button
|
Chrome 1 | Edge 12 | Firefox 1 | IE 9 | Opera 10.6 | Safari 3.1 | WebView Android 1 | Chrome Android 18 | Firefox Android 4 | Opera Android 11 | Safari iOS 2 | Samsung Internet Android 1.0 |
完整支持
MouseEvent