本函数的原理是调用document.execCommand
的copy
命令
document.execCommand("copy")
对不同浏览器的兼容性不同,详情请在这里参考
函数:
/*** 复制文本到剪切板* @param {String|Number} value 需要复制的文本* @return {Boolean}*/function copyText(value) {if (value == null || value === '') return falsevar textarea = document.createElement('textarea')textarea.value = valuedocument.body.appendChild(textarea)textarea.focus()textarea.setSelectionRange ? textarea.setSelectionRange(0, textarea.value.length) : textarea.select()var result = document.execCommand('copy')document.body.removeChild(textarea)return result}
用法示例:
// 直接复制文本copyText('demo')// 通过按钮实现复制指定元素的文本document.getElementById('button').addEventListener('click', function() {var text = document.getElementById("text").valuevar success = copyText(text)console.log(success ? '复制成功' : '复制失败')})