参考文档:https://developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommand
应用场景:在页面中,实现一键点击复制文案功能,免去用户手动复制
1、先在文档流中新建一个临时的 input 输入框元素
const Ele_input = document.createElement('input');
document.body.appendChild(Ele_input);
2、给该元素设置值,并选中(值即需要复制的文案)
Ele_input.setAttribute('value', '要复制的文案');
Ele_input.select(); // 选中输入框中需要复制的文案
3、调用 document.execCommand 方法来实现将文案复制到剪贴板
if(document.execCommand('copy')){
document.execCommand('copy');
alert('复制成功')
}else{
alert('复制失败,请手动复制');
}
4、删除临时的 input 元素
document.body.removeChild(Ele_input);
使用时将以上代码封装到一个方法中即可
function copy(v){
const Ele_input = document.createElement('input');
document.body.appendChild(Ele_input);
Ele_input.setAttribute('value', v);
Ele_input.select();
if(document.execCommand('copy')){
document.execCommand('copy');
alert('复制成功')
}else{
alert('复制失败,请手动复制');
}
document.body.removeChild(Ele_input);
}