用法:
Clipboard("复制内容",function(msg,txt){
//成功调用函数
console.log(msg,":",txt)
},function(msg){
//失败调用函数
console.log(msg)
});
功能实现代码:
function Clipboard(text, success, fail) {
// ------创建一个value为text且隐藏的textarea元素-------//
textArea = document.createElement('textArea')
textArea.value = text
textArea.style.opacity = '0'
textArea.setAttribute('readonly', 'readonly')
document.body.appendChild(textArea)
// --------------选择textarea中内容-------------------//
if (navigator.userAgent.match(/ipad|iphone/i)) {
window.getSelection().removeAllRanges()
let range = document.createRange()
range.selectNode(textArea)
window.getSelection().addRange(range)
textArea.setSelectionRange(0, 999999)
} else {
textArea.select()
}
// -------------------复制内容------------------------//
try {
if (document.execCommand('Copy')) {
success('复制成功!',text)
} else {
fail('复制失败!请手动复制!')
}
}
catch (err) {
fail('复制失败!请手动复制!')
}
// -------------------移除元素-----------------------//
window.getSelection().removeAllRanges()
document.body.removeChild(textArea)
}
网友评论