1:非input框的复制方式
动态创建input元素的方式实现复制
copyCode: function (val,e) {
let input = document.createElement('input');
input.setAttribute('readonly', 'readonly');//可设可不设
input.setAttribute('value', val);
//input.style.display='none'; 此处设置会影响复制功能,不能使用
input.className='fixed-class';//解决滚动条滚动的情况
document.body.appendChild(input);
input.focus();//选中前必须要focus
input.setSelectionRange(0, val.length);//选中的取值范围(全选)
//或者 input.setSelectionRange(0, -1); 全选
if (document.execCommand('copy')) {//判断是否存在该api;true为存在,false为不存在
document.execCommand('copy');//复制成功
console.log('复制成功');
}
document.body.removeChild(input);
}
2:input框的复制方式
var obj= document.getElementById("demo");//选中该input元素
obj.select(); //全选
// 或者 input.setSelectionRange(0, -1)
document.execCommand("copy");
推荐第一种方法;另外第一种方法可能会出现滚动条直接到底的情况,解决办法是为创建的元素添加一个固定定位的class即可解决;