完整代码
<!DOCTYPE html><html><head><meta charset="utf-8"><title>Copy</title></head><body><div id="box">点击复制文件内容!</div></body></html><script>box.addEventListener('click',(e)=>{window.getSelection().selectAllChildren(e.target);document.execCommand('copy')alert('复制成功')})</script>
window.getSelection
获取用户选中的文本或者光标停留的位置。
box.addEventListener('click',(e)=>{
console.log(
window.getSelection()
);
})
selectAllChildren
把指定元素的 所有子元素设为选中区域 ,并且取消之前选中的区域。
document.execCommand
已废弃。
document.execCommand('copy') // 拷贝内容
