Home >Web Front-end >JS Tutorial >JavaScript simulates mouse right-click menu effect_javascript skills

JavaScript simulates mouse right-click menu effect_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:12:131540browse

The example in this article shares the specific code for simulating the mouse right-click menu in JavaScript for your reference. The specific code is as follows
Rendering:

Specific code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>右键菜单</title>
  <style type="text/css">
    *{
      margin: 0;
      padding: 0;
    }
    #menu{
      width: 254px;
      /*background-color: #ccc;*/
      font-size: 12px;
      position: fixed;
      top: 0px;
      left: 0px;
      /*height: 240px;*/
      /*padding-left: 26px;*/
      padding-top: 2px;
      border:1px solid #ccc;
      display: none;
    }
    #menu li{
      list-style: none;
      line-height: 25px;
      margin-left: -1px;
      padding-left: 26px;
    }
    #menu li:hover{
      background-color: #4281f4;
      color: #fff;
    }
  </style>
</head>
<body>
   <ul id="menu">
     <li>返回(B)</li>
     <li>前进(F)</li>
     <li>从新加载(R)</li>
     <li>另存为(A)</li>
     <li>打印(P)</li>
     <li>查看网页源代码(V)</li>
     <li>查看网页信息(I)</li>
     <li>审查元素(N)</li>
   </ul>
   <script type="text/javascript">
    var menu = document.getElementById("menu");

    document.oncontextmenu =function(e){
      var e = e ||window.event;//兼容
     console.log(e.clientX,e.clientY);
     console.log(e);
     //单击显示div
     menu.style.display = "block";
     //设置定义
     //判断鼠标坐标是否大于视口宽度-块本身宽度
     var cakLeft = (e.clientX > document.documentElement.clientWidth - menu.offsetWidth)&#63;(document.documentElement.clientWidth - menu.offsetWidth):e.clientX;
     var cakTop = (e.clientY > document.documentElement.clientHeight - menu.offsetHeight)&#63;(document.documentElement.clientHeight - menu.offsetHeight):e.clientY;
     menu.style.left = cakLeft + "px";
     menu.style.top = cakTop + "px";

    return false;
    }

      menu.onclick = function(e) {
    var e = e || window.event;
    e.cancelBubble = true;
    //阻止冒泡。
  }
   document.onclick = function() {
    menu.style.display = "none";
  }
   
   </script>
</body>
</html>

I hope this article will be helpful to everyone in learning javascript programming.

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