一键复制其实在应用型网站中经常会用到,原理其实也是很简单的
第一步:创建一个textarea元素。
vartextArea=document.createElement(“textarea”);
第二步:给新创建的元素赋值
textArea.value=text;
第三步:将textArea元素插入到DOM中
document.body.appendChild(textArea);
第四步:选中textArea元素中的文本
textArea.select();
第五步:使用execCommand(‘copy’)实现复制
try{
varsuccessful=document.execCommand(‘copy’);
varmsg=successful?‘成功复制到剪贴板’:‘该浏览器不支持点击复制到剪贴板’;
alert(msg);
}catch(err){
alert(‘该浏览器不支持点击复制到剪贴板’);
}
第六步:移除刚创建的元素
document.body.removeChild(textArea);
以下是完整的函数代码,直接复制调用即可:
functioncopyToClipboard(text){if(text.indexOf(‘-‘)!==-1){letarr=text.split(‘-‘);text=arr[0]+arr[1];}vartextArea=document.createElement(“textarea”);textArea.style.position=‘fixed’;textArea.style.bottom=‘0’;textArea.style.left=‘0’;textArea.style.width=’20px’;textArea.style.height=’20px’;textArea.style.padding=‘0’;textArea.style.border=‘none’;textArea.style.outline=‘none’;textArea.style.boxShadow=‘none’;textArea.style.background=‘transparent’;textArea.value=text;document.body.appendChild(textArea);textArea.select();
try{varsuccessful=document.execCommand(‘copy’);varmsg=successful?‘成功复制到剪贴板’:‘该浏览器不支持点击复制到剪贴板’;alert(msg);}catch(err){alert(‘该浏览器不支持点击复制到剪贴板’);}
document.body.removeChild(textArea);}
以上就是原生js实现一键复制到剪切板的功能的全部功能,欢迎一起交流讨论前端哦
微信交流(备注:前端)