Home  >  Article  >  Web Front-end  >  js implements right-click menu function

js implements right-click menu function

高洛峰
高洛峰Original
2016-12-05 09:35:301689browse

Problems solved in this article: 1. Implement right-click menu function code; 2. Prevent the actual application of default events.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>右键菜单</title>
 <style type="text/css">
  #menu {
   position: fixed;
   left:0;
   top:0;
   width:200px;
   height: 400px;
   background-color: blue;
   display: none;
  }
 </style>
</head>
<body>
 <div id="menu">
 
 </div>
 <script type="text/javascript">
 var menu = document.getElementById("menu");
 document.oncontextmenu = function(e) {
  var e = e || window.event;
  //鼠标点的坐标
  var oX = e.clientX;
  var oY = e.clientY;
  //菜单出现后的位置
  menu.style.display = "block";
  menu.style.left = oX + "px";
  menu.style.top = oY + "px";
  //阻止浏览器默认事件
  return false;//一般点击右键会出现浏览器默认的右键菜单,写了这句代码就可以阻止该默认事件。
 }
 document.onclick = function(e) {
   var e = e || window.event;
   menu.style.display = "none"
  }
 menu.onclick = function(e) {
  var e = e || window.event;
  e.cancelBubble = true;
 }
 // document.addEventListener("contextmenu",function(e){
 // var e = e || window.event;
 // e.preventDefault();
 // alert("menu");
 // },false)
 </script>
</body>
</html>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn