JavaScript 实现复制文章自动添加版权信息的两种方案

作者:青柠

时间:2026-10-30

浏览:605

本文介绍两种利用 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> &copy; MySite.com";
  
 selection.selectAllChildren(newdiv);
 window.setTimeout(function () { body_element.removeChild(newdiv); }, 200);
});

总结

以上介绍了两种通过 JavaScript 实现复制文章时自动附加版权信息的技术方案,代码实现相对简单,有相关需求的技术人员可参考并集成到项目中。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章