做网站的时候经常有点击按钮复制文本的需求,在JS中通过以下5个步骤实现此功能:
基本方法
- 创建一个
<textarea>
元素对象,并将它的值设置为需要复制的文本字符串
- 将
<textarea>
元素对象append至html中
- 使用
HTMLInputElement.select()
方法选中 <textarea>
元素的内容
- 使用
Document.execCommand('copy')
将 <textarea>
元素内容复制到粘贴板中
- 移除
<textarea>
元素对象
代码类似如下:
1
2
3
4
5
6
7
8
|
const copyToClipboard = str => {
const el = document.createElement('textarea');
el.value = str;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
};
|
隐藏元素
以上方法会有个小问题,当append和remove <textarea>
元素的时候,页面可能会有闪动。我们将<textarea>
元素隐藏,并设置为只读属性。
1
2
3
4
5
6
7
8
9
10
11
|
const copyToClipboard = str => {
const el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', ''); // 只读
el.style.position = 'absolute';
el.style.left = '-9999px'; // 页面可视范围之外
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
};
|