GitHub 链接:https://github.com/zenorocha/clipboard.js
推荐阅读:《Cut and Copy Commands》
推荐阅读博客:《clipboard.js 核心代码解析》

一、核心概念原理

复制/剪切操作的实现,是去模拟键盘的「Ctrl+C」和「Ctrl+X」

  1. document.execCommand('copy') // 复制
  2. document.execCommand('cut') // 剪切

我们平时做复制/剪切操作,先要提前选择一段文本才行,同样地,这里使用代码来模拟这种操作

  1. let textNode = document.querySelector('.target') // 获取要复制目标节点
  2. let range = document.createRange()
  3. range.selectNode(textNode) // 创建一个范围
  4. window.getSelection().addRange(range) // 选中要复制的内容
  5. document.execCommand('copy') // 复制
  6. window.getSelection().removeAllRanges() // 取消选中

整体思路就是:用代码选中一段文本,做复制/剪切操作,然后再取消选中
注意:对于 input 和 textarea 元素,可以进行剪切操作,其他类型元素只能复制

二、简单使用

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width">
  6. <title>JS Bin</title>
  7. </head>
  8. <body>
  9. <div id="target">test1</div>
  10. <button class="button" data-clipboard-target="#target">点击我复制target</button>
  11. </body>
  12. </html>
  1. let button = document.querySelector('.button')
  2. button.onclick = (e)=>{
  3. let targetNode = document.querySelector(e.target.dataset.clipboardTarget)
  4. let range = document.createRange()
  5. range.selectNode(targetNode)
  6. window.getSelection().addRange(range)
  7. document.execCommand('copy')
  8. window.getSelection().removeAllRanges()
  9. }

「@浪里淘沙的小法师」