公司最近一个需求 需要通过变量实现复制。
代码块
window.copyText = item => {//挂载到全局
var textArea = document.createElement('textArea');
textArea.innerHTML = item;
textArea.value = item;
document.body.appendChild(textArea);
textArea.select();
try{
if(document.execCommand("Copy")){
alert(`${item} 复制成功!`)
}else{
alert('复制失败!请手动复制!')
}
}
catch(err){
alert('复制错误!请手动复制!')
}
document.body.removeChild(textArea);
}
使用的时候
window.copyText('今日头条!')