最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - addEventListener to right click event - Stack Overflow

programmeradmin3浏览0评论

I would like to add event listener to a right click event, i know how to deal with a simple click: document.getElementById("myBtn").addEventListener("mousedown", function(){ });

What about a right click event ?

I would like to add event listener to a right click event, i know how to deal with a simple click: document.getElementById("myBtn").addEventListener("mousedown", function(){ });

What about a right click event ?

Share Improve this question edited Aug 21, 2015 at 20:16 Khouloud asked Aug 21, 2015 at 18:28 KhouloudKhouloud 1111 gold badge1 silver badge10 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 9

Listen to the contextmenu event.

Just testing the click type using : alert("You pressed button: " + event.button)

document.body.addEventListener("mousedown", event => {
if (event.button == 0) { // left click for mouse
    alert("left click");
} else if (event.button == 1) { // wheel click for mouse
    alert("wheel click");
} else if (event.button == 2){   // right click for mouse
    alert("right click");
}});
<!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>
发布评论

评论列表(0)

  1. 暂无评论