HTML 鼠标点击复制元素内容

╰半夏微凉° 2022-12-30 10:44 272阅读 0赞

Intro

  • 效果展示

在这里插入图片描述

  • 方法封装

    copyInnerTextOfCell = (event) => {
    let innerText = event.target.innerText;
    var tmpInput = document.createElement(“input”);
    document.body.appendChild(tmpInput);
    tmpInput.value = innerText;
    tmpInput.select();
    document.execCommand(“cut”); // copy
    tmpInput.remove();
    alert(“复制成功!” + innerText);
    }

  • 原理、兼容性、替代方案
    官网文档:< https://developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommand>

    • 实现原理:使用了DOM原生的API document.execCommand(commandStr)
      当一个HTML文档切换到设计模式时,document暴露 execCommand 方法,该方法允许运行命令来操纵可编辑内容区域的元素。
    • 兼容性: 已废弃。
    • 替代方案/趋势:将来会被 Clipboard替代(需要用户授权后才能运行相关API)。

HTML

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>wuyujin1997</title>
  6. <script> copyInnerTextOfCell = (event) => { let innerText = event.target.innerText; var tmpInput = document.createElement("input"); document.body.appendChild(tmpInput); tmpInput.value = innerText; tmpInput.select(); document.execCommand("cut"); // copy tmpInput.remove(); alert("复制成功!" + innerText); } </script>
  7. </head>
  8. <body>
  9. <p onclick="copyInnerTextOfCell(event)">这是 p 标签内容</p>
  10. <div onclick="copyInnerTextOfCell(event)">这是 div 标签内容</div>
  11. <span onclick="copyInnerTextOfCell(event)">这是 span 标签内容</span>
  12. </body>
  13. </html>

More

其实核心代码就是通过 execCommand(“copy”) 把某些文本复制到系统剪贴板

至于是单击触发onClick事件
还是双击触发onDbClick事件
亦或是鼠标右键触发onContextMenu事件
或其他事件,都可以成为这个复制操作的触发点动作。

发表评论

表情:
评论列表 (有 0 条评论,272人围观)

还没有评论,来说两句吧...

相关阅读