2020更新
适用于所有 最新 浏览器的解决方案。
document.addEventListener('copy', (event) => { const pagelink = `nnRead more at: ${document.location.href}`; event.clipboardData.setData('text', document.getSelection() + pagelink); event.preventDefault();});Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br/><textarea name="textarea" rows="7" cols="50" placeholder="paste your copied text here"></textarea>[旧帖子-2020年更新之前]
向复制的Web文本添加额外信息的主要方法有两种。
1.操纵选择
这个想法是要注意
copy event,然后将带有额外信息的隐藏容器添加到,然后将
dom选择范围扩展到该容器。
这种方法适合从c.bavota。还要检查jitbit_的版本以了解更复杂的情况。
- 浏览器兼容性 :所有主要浏览器,IE> 8。
- Javascript代码 :
function addlink() { //Get the selected text and append the extra info var selection = window.getSelection(), pagelink = '<br /><br /> Read more at: ' + document.location.href, copytext = selection + pagelink, newdiv = document.createElement('div'); //hide the newly created container newdiv.style.position = 'absolute'; newdiv.style.left = '-99999px'; //insert the container, fill it with the extended text, and define the new selection document.body.appendChild(newdiv); newdiv.innerHTML = copytext; selection.selectAllChildren(newdiv); window.setTimeout(function () { document.body.removeChild(newdiv); }, 100);}document.addEventListener('copy', addlink);
2.操作剪贴板
这个想法是观看
copyevent并直接修改剪贴板数据。使用该
clipboardData属性是可能的。请注意,此属性可在中的所有主要浏览器中使用
read-only。该
setData方法仅在IE上可用。
- 浏览器兼容性 :IE> 4。
- Javascript代码 :
function addlink(event) { event.preventDefault(); var pagelink = 'nn Read more at: ' + document.location.href, copytext = window.getSelection() + pagelink; if (window.clipboardData) { window.clipboardData.setData('Text', copytext); }}document.addEventListener('copy', addlink);



