JS中自定义浏览器的右键行为

  • Post author:
  • Post category:其他


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    *{margin: 0; padding: 0;}
    ul{width: 100px;background-color: #fff; position: absolute; display: none;}
    li{width: 95px; border: 1px solid gray; line-height: 20px; padding-left: 3px;}
  </style>
</head>
<body>
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
  </ul>
  <script>
    window.onload = function() {
      // 自定义浏览器的右键行为
      var ul = document.querySelector('ul')
      document.oncontextmenu = (e) => {
        e = e || window.event
        e.preventDefault() //阻止默认行为
        // 将鼠标点击的坐标给到ul定位
        ul.style.top = e.clientY + 'px'
        ul.style.left = e.clientX + 'px'
        ul.style.display = 'block'
      }
    }
  </script>
</body>
</html>



版权声明:本文为weixin_42943920原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。