右击是Javascript事件吗?如果是,我该如何使用它?


当前回答

这是最简单的方法,它可以在所有浏览器上运行,除了应用程序web视图,如(CefSharp铬等…). 我希望我的代码能帮助到你,祝你好运!

const contentToRightClick=document.querySelector("div#contentToRightClick"); //const contentToRightClick=window; //If you want to add it into the whole document contentToRightClick.oncontextmenu=function(e){ e=(e||window.event); e.preventDefault(); console.log(e); return false; //Remove it if you want to keep the default contextmenu } div#contentToRightClick{ background-color: #eee; border: 1px solid rgba(0,0,0,.2); overflow: hidden; padding: 20px; height: 150px; } <div id="contentToRightClick">Right click on the box !</div>

其他回答

是的,oncontextmenu可能是最好的选择,但请注意,它在鼠标向下时触发,而单击将在鼠标向上时触发。

其他相关的问题是关于双击右键的——显然除了手动计时器检查外,不支持双击右键。您可能希望能够右双击的一个原因是,如果您需要/想要支持左手鼠标输入(按钮反转)。浏览器实现似乎对我们应该如何使用可用的输入设备做了很多假设。

窗口。Oncontextmenu =函数(e) { e.preventDefault () alert(右键) } <h1>请右键点击这里!< / h1 >

For track right click 

window.oncontextmenu = () =>{

console.log("Right click")

}

仅适用于右键单击

添加一个e.preventDefault来阻止菜单出现(以防你不想要它) 窗口。Oncontextmenu =函数(e) { e.preventDefault (); 警报(“你点击”); } <标题>右键单击< / h1 >

您可能想尝试以下属性:

按钮- (caniuse); Which - (caniuse)(弃用)。


function onMouseDown(e)
{
    if (e.which === 1 || e.button === 0)
    {
        console.log('Left mouse button at ' + e.clientX + 'x' + e.clientY);
    }

    if (e.which === 2 || e.button === 1)
    {
        console.log('Middle mouse button at ' + e.clientX + 'x' + e.clientY);
    }

    if (e.which === 3 || e.button === 2)
    {
        console.log('Right mouse button at ' + e.clientX + 'x' + e.clientY);
    }

    if (e.which === 4 || e.button === 3)
    {
        console.log('Backward mouse button at ' + e.clientX + 'x' + e.clientY);
    }

    if (e.which === 5 || e.button === 4)
    {
        console.log('Forward mouse button at ' + e.clientX + 'x' + e.clientY);
    }
}

window.addEventListener("mousedown", onMouseDown);

document.addEventListener("contextmenu", function(e)
{
    e.preventDefault();
});

相关:演示


操作系统

On Windows and Linux there are modifier keys Alt, Shift and Ctrl. On Mac there’s one more: Cmd, corresponding to the property metaKey... Even if we’d like to force Mac users to Ctrl+click – that’s kind of difficult. The problem is: a left-click with Ctrl is interpreted as a right-click on MacOS, and it generates the contextmenu event, not click like Windows/Linux. So if we want users of all operating systems to feel comfortable, then together with ctrlKey we should check metaKey. For JS-code it means that we should check if (event.ctrlKey || event.metaKey)...

在本章中,我们将详细介绍鼠标事件及其属性……

来源:https://amazon.com/dp/B07DZWLPG9