有可能得到鼠标按钮4、5等吗

Is it possible to get mouse buttons 4, 5, etc?

本文关键字:等吗 按钮 鼠标 有可能      更新时间:2024-04-21

简单地说,有没有任何方法可以检测JavaScript中的额外鼠标按钮按下?它没有与鼠标输入的其余部分一起记录,所以我想它不在标准实现中。

有没有什么方法,比如一个库,可以启用额外的鼠标按钮?

是的,您可以这样做,检查MouseEvent.button,请参阅下面的示例,该示例将检测3个和4个按钮的点击。

一些定点设备提供或模拟更多按钮。如中所述,为了表示这些按钮,每个连续按钮(二进制序列8、16、32…)的值必须加倍https://www.w3.org/TR/DOM-Level-3-Events/#events-鼠标事件

var whichButton = function (e) {
    // Handle different event models
    var e = e || window.event;
    var btnCode;
    if ('object' === typeof e) {
        btnCode = e.button;
        switch (btnCode) {
            case 3:
                console.log('Browser Back button clicked.');
            break;
            case 4:
                console.log('Browser Forward button clicked.');
            break;
            default:
                console.log('Unexpected code: ' + btnCode);
        }
    }
}
<button onmouseup="whichButton(event);" oncontextmenu="event.preventDefault();">Click with mouse...</button>

var whichButton = function (e) {
    // Handle different event models
    var e = e || window.event;
    var btnCode;
    if ('object' === typeof e) {
        btnCode = e.button;
        switch (btnCode) {
            case 3:
                console.log();
            break;
            case 4:
                console.log();
            break;
            default:
                console.log('Unexpected code: ' + btnCode);
        }
    }
}