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


当前回答

如果你想调用函数,而右击事件意味着我们可以使用以下

 <html lang="en" oncontextmenu="func(); return false;">
 </html>

<script>
function func(){
alert("Yes");
}
</script>

其他回答

如果你想调用函数,而右击事件意味着我们可以使用以下

 <html lang="en" oncontextmenu="func(); return false;">
 </html>

<script>
function func(){
alert("Yes");
}
</script>

是的,它是!

function doSomething(e) {
    var rightclick;
    if (!e) var e = window.event;
    if (e.which) rightclick = (e.which == 3);
    else if (e.button) rightclick = (e.button == 2);
    alert('Rightclick: ' + rightclick); // true or false
}
For track right click 

window.oncontextmenu = () =>{

console.log("Right click")

}

仅适用于右键单击

您可能想尝试以下属性:

按钮- (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

大多数使用mouseup或上下文菜单事件的给定解决方案在每次鼠标右键上升时触发,但它们不会检查鼠标右键之前是否下降。


如果您正在寻找一个真正的右键单击事件,该事件仅在同一元素中按下并释放鼠标按钮时触发,那么您应该使用auxclick事件。由于这将触发每个非主鼠标按钮,您还应该通过检查按钮属性过滤其他事件。

窗口。addEventListener("auxclick", (event) => { 如果事件。button === 2) alert("Right click"); });

你也可以通过在JavaScript开头添加以下代码来创建自己的右键事件:

{
  const rightClickEvent = new CustomEvent('rightclick', { bubbles: true });
  window.addEventListener("auxclick", (event) => {
    if (event.button === 2) {
      event.target.dispatchEvent(rightClickEvent);
    }
  });
}

然后你可以通过addEventListener方法监听右键事件,如下所示:

your_element.addEventListener("rightclick", your_function);

在MDN上阅读更多关于auxclick事件的信息。