1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > js 复制文本到剪切板 document.execCommand(“copy“)

js 复制文本到剪切板 document.execCommand(“copy“)

时间:2020-01-12 04:53:59

相关推荐

js 复制文本到剪切板 document.execCommand(“copy“)

本函数的原理是调用document.execCommandcopy命令

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 ? '复制成功' : '复制失败')})

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。