<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>js 实现往web端选中内容添加自定义内容代码(类csdn代码版权效果)</title>
</head>
<body>
<p id="content-holder">微信头像更换小国旗的最新相关信息2小时前 国旗做微信头像违法?发完朋友圈,网友慌了!律师说法.</p>
<button id="copy-button">Copy Text</button>
<textarea placeholder="Paste here"></textarea>
</body>
<script>
function addLink() {
let body_element = document.body;
let selection = window.getSelection();
let locationHref=document.location.href;
let appendLink="\r\n\r\n 原文出自[ zyc博客 ] 转载请保留原文链接: <a href='"+locationHref+"'>"+locationHref+"</a>";
if (window.clipboardData) { // Internet Explorer 兼容
let copytext = selection + appendLink;
window.clipboardData.setData ("Text", copytext);
return false;
} else {
let copytext = selection + appendLink;
let newdiv = document.createElement('div');
body_element.appendChild(newdiv);
newdiv.innerHTML = copytext;
selection.selectAllChildren(newdiv);
console.log(copytext);
window.setTimeout(function() {
body_element.removeChild(newdiv);
},0);
}
}
document.oncopy = addLink;
</script>
</html>
运行效果: