开发web端页面时,经常需要复制页面文本到剪贴板,比如页面展示订单号、物流单号等,我们使用js原生的document.execCommand实现复制功能
方法一:页面纯在输入框方法
1、在页面添加input框,给button绑定点击事件
<input type="text" id="copy-input" readOnly="readOnly" value="hello world">
<button @click="copy">复制</button>
添加readOnly只读属性,避免移动端弹出虚拟键盘
2、写copy方法
const input = document.getElementById('copy-input')
input.select()
document.execCommand('copy')
注意:
- input框不能有disabled属性
- 根据第一条扩展,input的width || height 不能为0;
- input框不能有hidden属性
如果不想在页面上显示input输入框,可以使用创建input节点的方式,给value赋值,append到页面上,复制完了,再remove节点
方法二:纯js添加Dom元素并复制
const str = "需要复制的内容";
const inputo = document.createElement("input");
document.body.appendChild(inputo);
inputo.value = str;
inputo.setAttribute('readOnly', 'readOnly')
inputo.select();
document.execCommand("Copy");
document.body.removeChild(inputo);
2805

被折叠的 条评论
为什么被折叠?



