# 如何实现选中复制的功能
更多描述
在一些博客系统,如掘金的博客中,可以复制代码,它是如何实现的
Issue
欢迎在 Issue 中交流与讨论: Issue 20 (opens new window)
Author
它一般可以使用第三方库 clipboard.js (opens new window) 来实现,源码很简单,可以读一读
主要有两个要点
- 选中:
Selection API
- 复制:
document.execCommand
# 选中: Selection API/Range API
选中主要利用了 Selection API (opens new window) 与 Range API
选中的代码如下
const selection = window.getSelection();
const range = document.createRange();
// RangeAPI: 制造区域
range.selectNodeContents(element);
// Selection: 选中区域
selection.addRange(range);
selectedText = selection.toString();
取消选中的代码如下
window.getSelection().removeAllRanges();
它有现成的第三方库可以使用: select.js (opens new window)
# 复制: execCommand
复制就比较简单了,execCommand
document.exec('copy')