h5中实现兼容性比较好的点击复制方法,代码如下
function copy(text){
function selectText(textbox,startIndex,stopIndex){
if(textbox.createTextRange){
const range=textbox.createTextRange();
range.moveStart('character',startIndex);
range.moveEnd('character',startIndex-stopIndex);
range.select();
}else{
textbox.setSelectionRange(startIndex,stopIndex);
textbox.focus();
}
}
return new Promise((resolve,reject)=>{
let textArea=document.createElement('textarea');
textArea.style.position='fixed';
textArea.style.top='-10000';
textArea.style.zIndex='-1';
textArea.readOnly='readOnly';
textArea.value= text;
document.body.appendChild(textArea);
selectText(textArea,0,text.length)
try{
if(document.execCommand('copy')){
document.execCommand('copy')
resolve();
}else{
reject('当前浏览器不支持该复制方法');
}
} catch(error){
reject(error)
}
textArea.blur();
document.body.removeChild(textArea);
})
}
copy('张三').then(res=>{console.log('复制成功')}).catch(()=>{console.log('复制失败')})