Detect left mouse button press

后端 未结 5 1780
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 06:44

I hate this mess with the mouse buttons created by W3C an MS! I want to know if the left mouse button is pressed when I get a mousedown event.

I use this code

5条回答
  •  情歌与酒
    2020-11-29 07:10

    There is now a W3C standard event.buttons property supported by IE9 in standards mode, and Gecko 15+.

    The W3C completely stuffed up the event.button property, so for a standards compliant browser event.button is 0, but for browsers created before the standard, event.button is 1.

    So code must avoid using event.button except for older browsers. The following code should work:

    function detectLeftButton(event) {
        if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) {
            return false;
        } else if ('buttons' in event) {
            return event.buttons === 1;
        } else if ('which' in event) {
            return event.which === 1;
        } else {
            return (event.button == 1 || event.type == 'click');
        }
    }
    

提交回复
热议问题