JavaScript 实现复制文章自动添加版权信息的两种方案
作者:青柠时间:2026-10-30 11:31:58浏览:606
本文介绍两种利用 JavaScript 在用户复制网页内容时自动追加版权信息的方法。第一种基于原生 JS 的 oncopy 事件与 clipboardData 对象,需注意代码需置于 body 中;第二种采用 jQuery 绑定 copy 事件,通过动态创建临时 div 处理选中内容,并包含对短文本和旧版浏览器的兼容处理。
原生 JavaScript 实现复制添加版权
第一种方法
<script type="text/javascript">
document.body.oncopy = function(){
setTimeout(
function (){
var text = clipboardData.getData("text");
if(text){
text = text + "\r\n本文来自: (www.jb51.net) 详细出处参考:"+location.href; clipboardData.setData("text", text);
}
},100)
}
</script>
需要特别注意,上述代码必须放置在 HTML 的 body 标签内部才能正常生效,若将其放置在 head 区域则无法执行。
jQuery 方案处理复制事件
第二种方法
$("body").bind('copy', function (e) {
if (typeof window.getSelection == "undefined") return; //IE8 or earlier...
var body_element = document.getElementsByTagName('body')[0];
var selection = window.getSelection();
//if the selection is short let's not annoy our users
if (("" + selection).length < 30) return;
//create a div outside of the visible area
//and fill it with the selected text
var newdiv = document.createElement('div');
newdiv.style.position = 'absolute';
newdiv.style.left = '-99999px';
body_element.appendChild(newdiv);
newdiv.appendChild(selection.getRangeAt(0).cloneContents());
//we need a <pre> tag workaround
//otherwise the text inside "pre" loses all the line breaks!
if (selection.getRangeAt(0).commonAncestorContainer.nodeName == "PRE") {
newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
}
newdiv.innerHTML += "<br /><br />Read more at: <a href='"
+ document.location.href + "'>"
+ document.location.href + "</a> © MySite.com";
selection.selectAllChildren(newdiv);
window.setTimeout(function () { body_element.removeChild(newdiv); }, 200);
});
总结
以上介绍了两种通过 JavaScript 实现复制文章时自动附加版权信息的技术方案,代码实现相对简单,有相关需求的技术人员可参考并集成到项目中。
作者最新文章
JS读取本地文件时报错或无响应的常见原因
2026-11-05 16:32:31
let、const与var的区别:JavaScript变量声明最佳实践
2026-11-05 14:16:38
JS中直接定义静态二维数组的字面量写法
2026-11-05 14:16:08
JS 怎么查找字符串中所有匹配项的位置
2026-11-05 14:15:53
JavaScript新手常犯的编码错误与最佳实践指南
2026-11-04 22:12:38
