因为项目需要,用到了这个,就在这里记录一下。关于粘贴板的更多操作,等以后用到了,再继续添加。。。
<body>
<div id='str'>helloworld</div>
<button onclick='copy()'>点击复制上面的文字</button>
</body>
<script>
function copy() {
var copy = document.getElementById('str')
if (document.body.createTextRange) { // 该属性只有IE支持
var range = document.body.createTextRange()
range.moveToElementText(copy)
range.select()
document.execCommand('Copy')
alert('已复制1')
} else if (window.getSelection) {
var selection = window.getSelection()
selection.removeAllRanges()
var range = document.createRange()
range.selectNodeContents(copy)
selection.addRange(range)
document.execCommand('Copy')
selection.removeAllRanges()
alert('已复制2')
}
}
</script>