- 方法一 document.execCommand
- 非input / textarea中的复制
tryCopy() {
let copyWrapper = document.querySelector(".copy-wrapper");
// 创建select对象与range对象
const selection = window.getSelection();
const range = document.createRange();
// 从当前selection对象中移除所有的range对象,
// 取消所有的选择只 留下anchorNode 和focusNode属性并将其设置为null。
// 这里没弄明白为什么需要先remove一下, 也没有太多资料查证 没有这句会复制失败
if (selection.rangeCount > 0) selection.removeAllRanges();
// 使 Range 包含某个节点的内容 使用这个 或者下面的selectNode都可以
// range.selectNodeContents(tx)
// 使 Range 包含某个节点及其内容
range.selectNode(copyWrapper);
// 向选区(Selection)中添加一个区域(Range)
selection.addRange(range);
// 已复制文字
// console.log('selectedText', selection.toString())
// 执行浏览器复制命令
document.execCommand("copy");
}
- 实现input / textarea中的复制
使用input / textarea进行复制操作 这种方式更加简单 因为二者有一个select() 函数更便捷的复制而不需要去创建select对象与range对象
let input = document.createElement('input')
input.setAttribute('readonly', 'readonly') // 防止手机上弹出软键盘
input.setAttribute('value', txval) // txval 为所需复制的值 变量 或者 写死
document.body.appendChild(input)
input.select()
document.execCommand('copy')
document.body.removeChild(input)
但是此处注意 当你的txval为多个值拼接 并需要在剪贴板换行时 此方法无法满足,要实现换行请使用textarea
- 方法二 navigator.clipboard
使用navigator.clipboard
直接执行报错 DOMException: Document is not focused
,需要用户主动触发,如click中执行
const copyText = async (text) => await navigator.clipboard.writeText(text)
document.querySelector('body').addEventListener('click', () => {copyText('复制文本内容');console.log('已复制')})