javascript - h5复制到剪切板
本文介绍了javascript - h5复制到剪切板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
参考地址:https://segmentfault.com/a/11...
demo地址:http://codepen.io/JimmyVV/pen...
单独访问没问题,只要放进项目,第一次报错,复制不成功,第二次之后就可以了
// 复制链接地址并关闭分享且提醒
var aEle = document.querySelector('#copy');
aEle.addEventListener('click',function(){
var copyDOM = document.querySelector('#selector');
var range = document.createRange();
range.selectNode(copyDOM);
window.getSelection().addRange(range);
var successful = document.execCommand('copy');
try {
// Now that we've selected the anchor text, execute the copy command
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copy email command was ' + msg);
} catch(err) {
console.log('Oops, unable to copy');
}
// Remove the selections - NOTE: Should use
// removeRange(range) when it is supported
window.getSelection().removeAllRanges();
},false);
解决方案
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
addRange
之前先remove
这篇关于javascript - h5复制到剪切板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文