js监听复制和粘贴
html
<body>
<p id="content">我是复制的内容</p>
<button id="btn" onclick="copy()">复制按钮</button>
<textarea name="text" id="text" cols="30" rows="10"></textarea>
<script>
var content = document.getElementById('content')
var btn = document.getElementById('btn')
var text = document.getElementById('text')
console.log(window.getSelection)
/* 监听复制,加上后缀 */
content.oncopy = function (e) {
var text = window.getSelection()
if (!window.clipboardData) {
e.preventDefault()
e.clipboardData.setData('text/plain', text + "\r\n\r\n 原文出自[ maps131 ]googel")
} else { // ie
var copytext = text + "\r\n\r\n 原文出自[ maps131 ]ie"
var newdiv = document.createElement('div')
document.body.appendChild(newdiv)
newdiv.innerText = copytext
text.selectAllChildren(newdiv)
window.setTimeout(function() {
document.body.removeChild(newdiv);
}, 0)
}
}
/* 监听粘贴 */
text.onpaste = function (e) {
if (e.clipboardData) {
console.log(e.clipboardData.getData('Text'))
return
}
/* ie */
console.log(window.clipboardData.getData('Text'))
}
/* 按钮复制 */
function copy() {
var selection = window.getSelection()
var range = document.createRange()
range.selectNode(content)
selection.removeAllRanges()
selection.addRange(range)
document.execCommand("Copy")
}
</script>
</body>
JStar