修改鼠标右键自定义事件

707 阅读1分钟

效果图如下

image.png

实现方式如下:

1.先找到想要阻止默认鼠标右键事件的节点,然后屏蔽默认右键菜单弹出。

2.创建自定义菜单节点和编写相关样式,以及添加右键子项的监听事件和处理方法。

3.处理右键点击事件重复创建的问题,遍布找到已经创建的右键菜单节点,把它移除,最后是点击页面时把右键弹窗菜单给隐藏掉。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #myButton {
        font-size: 16px;
      }
      .customMenu {
        background: #ffffff;
        border-radius: 8px;
        box-shadow: 0 2px 10px 2px #d1d1d1;
        padding: 10px 0;
      }
      .rightBtnOption {
        padding: 5px 20px;
        font-size: 14px;
      }
      .rightBtnOption:hover {
        background: #f2f2f2;
      }
    </style>
  </head>
  <body>
    <div>
      <button id="myButton">按钮右键点击</button>
    </div>
    <script>
      // 监听鼠标右键点击事件
      document.getElementById("myButton").addEventListener("contextmenu", function (event) {
        event.preventDefault(); // 阻止默认的右键菜单弹出

        //移除已创建的右键标签
        const domEls = document.getElementsByClassName("customMenu");
        Array.from(domEls).forEach((el) => {
          document.body.removeChild(el);
        });

        // 创建自定义菜单
        var customMenu = document.createElement("div");
        customMenu.id = "custom-menu";
        customMenu.style.position = "fixed";
        customMenu.style.top = event.clientY + 10 + "px";
        customMenu.style.left = event.clientX + 10 + "px";
        customMenu.className = "customMenu";

        // 添加自定义选项
        var option1 = document.createElement("div");
        option1.innerHTML = "自定义选项1";
        option1.style.cursor = "pointer";
        option1.className = "rightBtnOption";
        option1.addEventListener("click", function () {
          // 点击自定义选项1的操作
          console.log("点击了自定义选项1");
          customMenu.remove(); // 点击后移除自定义菜单
        });
        customMenu.appendChild(option1);

        var option2 = document.createElement("div");
        option2.innerHTML = "自定义选项2";
        option2.style.cursor = "pointer";
        option2.className = "rightBtnOption";
        option2.addEventListener("click", function () {
          // 点击自定义选项2的操作
          console.log("点击了自定义选项2");
          customMenu.remove(); // 点击后移除自定义菜单
        });
        customMenu.appendChild(option2);

        // 将自定义菜单添加到页面
        document.body.appendChild(customMenu);

        // 点击页面其他地方移除自定义菜单
        document.addEventListener(
          "click",
          function () {
            customMenu.remove();
          },
          { once: true }
        );
      });
    </script>
  </body>
</html>