event.button

概述

表明当前事件是由鼠标的哪个按键触发的.

语法

event.button

例子

var buttonCode = event.button;

该属性返回一个整数值,代表触发当前事件的鼠标按键.在通常情况下,对应关系如下:

  • 0 为 左键点击.
  • 1 为 中键点击.
  • 2 为 右键点击.
注意: IE不遵守 See QuirksMode for details.

The order of buttons may be different depending on how the pointing device has been configured.

例子

<script>
var whichButton = function (e) {
    // 处理不同的事件模型
    var e = e || window.event;
    var btnCode;

    if ('object' === typeof e) {
        btnCode = e.button;

        switch (btnCode) {
            case 0:
                alert('你按了左键.');
            break;
            case 1:
                alert('你按了中键.');
            break;
            case 2:
                alert('你按了右键.');
            break;
            default:
                alert('未知按键: ' + btnCode);
        }
    }
}
</script>

<button onmouseup="whichButton(event);" oncontextmenu="event.preventDefault();">请点击鼠标...</button>

备注

Because mouse clicks are frequently intercepted by the user interface, it may be difficult to detect buttons other than those for a standard mouse click (usually the left button) in some circumstances.

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.

规范

DOM 2 Events Specification: button

浏览器兼容性

Based on Jan Wolter's JavaScript Madness: Mouse Events.

Feature Gecko Webkit Internet Explorer Opera
Basic support 1 523 9 8

文档标签和贡献者

 此页面的贡献者: ziyunfei, teoli, AshfaqHossain
 最后编辑者: AshfaqHossain,