Is right click a Javascript event?

后端 未结 18 2329
南笙
南笙 2020-11-22 10:02

Is right click a Javascript event? If so, how do I use it?

18条回答
  •  不知归路
    2020-11-22 10:21

    As others have mentioned, the right mouse button can be detected through the usual mouse events (mousedown, mouseup, click). However, if you're looking for a firing event when the right-click menu is brought up, you're looking in the wrong place. The right-click/context menu is also accessible via the keyboard (shift+F10 or context menu key on Windows and some Linux). In this situation, the event that you're looking for is oncontextmenu:

    window.oncontextmenu = function ()
    {
        showCustomMenu();
        return false;     // cancel default menu
    }
    

    As for the mouse events themselves, browsers set a property to the event object that is accessible from the event handling function:

    document.body.onclick = function (e) {
        var isRightMB;
        e = e || window.event;
    
        if ("which" in e)  // Gecko (Firefox), WebKit (Safari/Chrome) & Opera
            isRightMB = e.which == 3; 
        else if ("button" in e)  // IE, Opera 
            isRightMB = e.button == 2; 
    
        alert("Right mouse button " + (isRightMB ? "" : " was not") + "clicked!");
    } 
    

    window.oncontextmenu - MDC

提交回复
热议问题