封装函数参数 id:要复制的元素id,paramtype:复制的属性内容,一般是innerText;
copywxid(id, paramtype) {
let target = null;
if (paramtype) {
target = document.createElement('div');
target.id = 'tempTarget';
target.style.opacity = '0';
if (id) {
let curNode = document.querySelector('#' + id);
target.innerText = curNode[paramtype];
} else {
target.innerText = paramtype;
}
document.body.appendChild(target);
} else {
target = document.querySelector('#' + id);
}
try {
let range = document.createRange();
range.selectNode(target);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
document.execCommand('copy');
window.getSelection().removeAllRanges();
console.log('成功复制啦啦');
} catch (e) {
console.log('复制失败呀');
}
if (paramtype) {
target.parentElement.removeChild(target);
}
},
原理总结;
1.先创建全透明div,并把要复制的内容放入其innerText
2.创建range对象,并选中id元素的节点
3.清除全部range对象,避免多余内容,
4.新增本次定义的range对象
5.使用execcommand(‘copy’)命令,复制内容
6.console.log可根据ui框架换成弹窗提示,