在右键单击事件上添加addEventListener方法

3

我想在右键事件上添加一个事件监听器,我知道如何处理简单的单击事件:

document.getElementById("myBtn").addEventListener("mousedown", function(){ });

那么右键点击事件呢?

4个回答

7

我还在监听鼠标点击事件,问题是程序将右键点击也视为普通点击,如何区分它们? - Khouloud
@Khouloud,“程序将右键单击检测为单击”。不,它没有。你正在监听mousedown事件而不是click事件。请改为监听click事件而不是mousedown事件! - Ram

2

只是测试点击类型,使用: alert("您按下的按钮是:" + event.button)


0
document.body.addEventListener("mousedown", event => {
    if (event.button == 0) { // left click for mouse
        doSomething;
    else if (event.button == 1) { // right click for mouse
        doAnotherThing;
    else {   // other buttons on the mouse
        doOtherThings;
    }
}

1
根据https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button,`button`属性为`1`表示“按下辅助按钮,通常是滚轮按钮或中间按钮(如果有)”,右键鼠标为`2`。这也符合我的经验(在Windows 10上)。 - DLosc
@DLosc是对的,我稍微修改了代码,通过了我本地环境的测试。 - undefined

0
<!DOCTYPE html>
<html>
<head>
<style>
div { background: yellow; border: 1px solid black; padding: 10px; } 
div {
    background: yellow;
    border: 1px solid black;
    padding: 10px;
}
</style>
</head>
<body>
<div oncontextmenu="myFunction(event)">
<p>Right-click inside this box to see the context menu!
</div>
<script>
function myFunction(e) {
  e.preventDefault();
  //do something differant context menu
  alert("You right-clicked inside the div!");
}
</script>
<!--if it helpful visit once http://topprojects.ml for more stuf-->
</body>
</html>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接