/*
copyNodeText → 传入选择器实现对某个dom元素内部的文本文字进行复制
[
copyNodeText函数仅限标签包裹文本的情况
不适用于这种情况↓
<div class="need-copy">
css3
<span>需要复制的文本</span>
</div>
]
copyNodeText函数的参数写一个css选择器即可
使用例子
你希望复制 <div class="need-copy">123</div>内的文本文字
则需要调用函数 → copyNodeText(".need-copy")即可
*/
const copyNodeText = (cssSelector) => {
const needCopyDom = document.querySelector(cssSelector)
if (!needCopyDom) {
console.log('dom元素获取失败,请在copyNodeText函数调用时传入 规范正确 的css选择器 !!!')
return false
} else {
const range = document.createRange() // 创建一个range对象
range.selectNode(needCopyDom) // 创建一个selection对象
const selection = window.getSelection() // 创建selection对象
if (selection.rangeCount > 0) {
// 如果页面已经有选取的话,会自动删除这个选区,没有选区的话,会把这个选取加入选区
selection.removeAllRanges()
}
selection.addRange(range) // 将range对象添加到selection选区当中,会高亮文本块
document.execCommand('copy')
selection.removeRange(range)
return true
}
}
前端js实现复制页面上的文字到剪贴板中
最新推荐文章于 2023-12-26 22:00:44 发布