主要分一下几步
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); // 移除插入的文本域节点
}