要实现右键复制粘贴功能,你可以使用 JavaScript 中的 document.execCommand() 方法。下面是一个简单的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>右键复制粘贴功能</title>
  </head>
  <body>
    <input type="text" id="myInput" value="Hello, World!">
    
    <script>
      // 获取输入框元素
      var input = document.getElementById("myInput");

      // 右键菜单事件监听
      document.addEventListener("contextmenu", function(event) {
        event.preventDefault(); // 阻止默认右键菜单

        // 创建右键菜单
        var menu = document.createElement("div");
        menu.style.position = "fixed";
        menu.style.top = event.clientY + "px";
        menu.style.left = event.clientX + "px";
        menu.style.background = "#f2f2f2";
        menu.style.padding = "10px";
        menu.innerHTML = `
          <button onclick="copyText()">复制</button>
          <button onclick="pasteText()">粘贴</button>
        `;

        // 添加右键菜单到页面
        document.body.appendChild(menu);

        // 点击其他地方时,移除右键菜单
        document.addEventListener("click", function() {
          document.body.removeChild(menu);
        });
      });

      // 复制文本到剪贴板
      function copyText() {
        input.select();
        document.execCommand("copy");
      }

      // 将剪贴板中的文本粘贴到输入框
      function pasteText() {
        input.focus();
        document.execCommand("paste");
      }
    </script>
  </body>
</html>

在这个示例中,我们创建了一个输入框和一个右键菜单。当右键点击页面时,阻止默认右键菜单,并显示我们创建的右键菜单。右键菜单中有两个按钮,分别调用 copyText()pasteText() 函数来执行复制和粘贴操作。

copyText() 函数将输入框的文本选中,并使用 document.execCommand("copy") 方法将文本复制到剪贴板。

pasteText() 函数将输入框聚焦,并使用 document.execCommand("paste") 方法将剪贴板中的文本粘贴到输入框中

js 实现右键复制粘贴功能

原文地址: https://www.cveoy.top/t/topic/ieHs 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录