主要分一下几步
1、创建一个文本域节点
var textArea = document.createElement(‘textarea’);
2、把要复制的内容插入到上面创建的文本域节点里
textArea.textContent = ‘我是被复制的内容’;
3、设置创建的文本域节点style
textArea.style.position = ‘fixed’;
4、把创建的文本节点插入到body里
document.body.appendChild(textArea);
5、选择创建的文本域节点
textArea.select();
6、try {} catch() {}捕获异常
try {
document.execCommand(‘copy’); // 把要复制的内容拷贝到剪贴板
alert(‘复制成功’);
} catch(ex) {
alert(‘复制失败’);
return false;
} finally {
document.body.removeChild(textArea); // 移除插入的文本域节点
}
本文介绍了如何使用JavaScript创建一个隐藏的文本域,将指定内容插入并选中,然后调用`document.execCommand('copy')`来实现文本的复制到剪贴板。这个方法适用于在网页上提供一键复制功能,例如复制代码片段或者重要信息。
1155





