在javascript中document.execCommand()方法是将文字复制到粘贴板,然后复制到其他地方使用。具体的实现方法可以如下:
copyToClipboard(txt = '') {
let iscopy = false;
if (document) {
let textArea = document.createElement('textarea');
textArea.style.position = 'fixed';
textArea.style.top = 0;
textArea.style.left = 0;
textArea.style.width = '2em';
textArea.style.height = '2em';
textArea.style.padding = 0;
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.boxShadow = 'none';
textArea.style.background = 'transparent';
textArea.value = txt;
document.body.appendChild(textArea);
textArea.select();
try {
document.execCommand('copy');
iscopy = true;
} catch (err) {
console.log('不能使用这种方法复制内容' + err.toString());
}
document.body.removeChild(textArea);
}
return iscopy;
}
注意
- 1.解决兼容性问题(根据不同浏览器用不同的实现方式,这里是谷歌浏览器,该方法最新浏览器基本兼容)
- 2.不能用JS“直接”调用execCommand('copy'),需要放到某一个由用户触发的事件响应函数内,而且之间不能被异步过程隔开,诸如 setTimeout。
网友评论