2022 年更新
处理富文本格式的更复杂的解决方案。如果您只处理纯文本,2020 年的解决方案仍然适用。
const copyListener = (e) => {
const range = window.getSelection().getRangeAt(0),
rangeContents = range.cloneContents(),
pageLink = `Read more at: ${document.location.href}`,
helper = document.createElement("div");
helper.appendChild(rangeContents);
event.clipboardData.setData("text/plain", `${helper.innerText}\n${pageLink}`);
event.clipboardData.setData("text/html", `${helper.innerHTML}<br>${pageLink}`);
event.preventDefault();
};
document.addEventListener("copy", copyListener);
#richText {
width: 415px;
height: 70px;
border: 1px solid #777;
overflow: scroll;
}
#richText:empty:before {
content: "Paste your copied text here";
color: #888;
}
<h4>Rich text:</h4>
<p>Lorem <u>ipsum</u> dolor sit <b>amet</b>, consectetur <i>adipiscing</i> elit.</p>
<h4>Plain text editor:</h4>
<textarea name="textarea" rows="5" cols="50" placeholder="Paste your copied text here"></textarea>
<h4>Rich text editor:</h4>
<div id="richText" contenteditable="true"></div>
2020 年更新
适用于所有近期浏览器的解决方案。
请注意,即使粘贴到富文本编辑器中,此解决方案也会去除富文本格式(例如粗体和斜体)。
document.addEventListener('copy', (event) => {
const pagelink = `\n\nRead more at: ${document.location.href}`;
event.clipboardData.setData('text/plain', document.getSelection() + pagelink);
event.preventDefault();
});
Lorem ipsum dolor sit <b>amet</b>, consectetur <i>adipiscing</i> elit.<br/>
<textarea name="textarea" rows="7" cols="50" placeholder="paste your copied text here"></textarea>
[较早的帖子 - 2020 年更新之前]
向复制的网络文本添加额外信息的主要方法有两种。
- 操作选择
我们的想法是监视copy event,然后将带有我们额外信息的隐藏容器附加到dom,并将选择扩展到它。
此方法改编自 c.bavota 的 this article。更复杂的情况也请查看jitbit's version。
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);
- 操作剪贴板
思路是看copy event,直接修改剪贴板数据。这可以使用clipboardData 属性来实现。请注意,该属性在read-only中的所有主要浏览器中都可用; setData 方法仅适用于 IE。
function addLink(event) {
event.preventDefault();
var pagelink = '\n\n Read more at: ' + document.location.href,
copytext = window.getSelection() + pagelink;
if (window.clipboardData) {
window.clipboardData.setData('Text', copytext);
}
}
document.addEventListener('copy', addLink);