一键复制表格内容:
function copyTable() {
const table = document.getElementById('table')
const range = document.createRange()
// 设定range包含的节点对象
range.selectNode(table)
// 窗口的selection对象,表示用户选择的文本
const selection = window.getSelection()
// 将已经包含的已选择的对象清除掉
if (selection.rangeCount > 0) selection.removeAllRanges()
// 将要复制的区域的range对象添加到selection对象中
selection.addRange(range)
// 执行copy命令,copy用户选择的文本
document.execCommand('copy')
}
一键复制文字内容:
function copyText(value) {
let transfer = document.createElement('input')
document.body.appendChild(transfer)
transfer.value = value; // 这里表示想要复制的内容
transfer.focus()
transfer.select()
if (document.execCommand('copy')) {
document.execCommand('copy')
}
transfer.blur()
console.log('复制成功')
document.body.removeChild(transfer)
}