# 如何实现选中复制的功能
在一些博客系统,如掘金的博客中,可以复制代码,它是如何实现的
Issuse 链接,欢迎交流,欢迎 Star: 【Q019】如何实现选中复制的功能 (opens new window)
它一般可以使用第三方库 clipboard.js (opens new window) 来实现,源码很简单,可以读一读
主要有两个要点
- 选中
- 复制
# 选中
选中主要利用了 Selection API (opens new window)
选中的代码如下
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
selectedText = selection.toString();
取消选中的代码如下
window.getSelection().removeAllRanges();
它有现成的第三方库可以使用: select.js (opens new window)
# 复制
复制就比较简单了,execCommand
document.exec('copy')