在我们日常开发过程中,经常会遇到需要复制文末内容的需求,那么这个时候我们就可以使用document.execCommand()进行来实现这个需求。
具体的实现思路如下:
- 创建一个
textarea; - 将需要复制的值赋值给该
textarea; - 通过
element.select()方法选中textarea中的内容 - 最后通过调用
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对其进行兼容处理。
本文介绍了如何利用JavaScript的document.execCommand()方法在网页中实现文本复制功能。通过创建隐藏的textarea,将目标文本赋值并选中,然后调用execCommand('copy')进行复制。此方法已在Jsutil库中发布,虽然不推荐,但目前仍被部分浏览器支持。未来计划使用ClipboardApi进行兼容性处理。
635

被折叠的 条评论
为什么被折叠?



