参考地址: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);
addRange
之前先remove