js复制文本信息——Jsutil类
在我们日常开发过程中,经常会遇到需要复制文末内容的需求,那么这个时候我们就可以使用document.execCommand()进行来实现这个需求。
具体的实现思路如下:
1、创建一个textarea;
2、将需要复制的值赋值给该textarea;
3、通过element.select()方法选中textarea中的内容
4、最后通过调用document.execCommand('copy')进行内容的复制
具体操作如下:
function CopyText(str) { // 1.创建一个input元素 let input = document.createElement('textarea') // 2.将传入的值赋值给textarea input.value = str // 3.设置文本域的相关属性,避免在body中添加该元素对页面造成影响 input.style.width = '0' input.style.height = '0' input.style.position = 'fixed' input.style.opacity = '0' // 4.将当前文本域插入到body document.body.appenChild(input) // 5.选中文本域中的内容 input.select(); // 6.通过调用execCommnd()方法赋值内容 document.execCommnd('copy') // 7.最后移除该元素 document.body.removeChild(input) }
本篇文章中的方法已发布在Jsutil库中,该库为一个功能性的函数库,欢迎大家引用及Star或者提出宝贵的意见。
事实上document.execCommand特性已不再被推荐使用,但目前一些浏览器仍然支持它。后续会基于Clipboard Api对其进行兼容处理。