DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> JavaScript實現復制文章自動添加版權
JavaScript實現復制文章自動添加版權
編輯:關於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> 

注意:這段代碼必須復制到 body 區域裡面才能生效,放到 head 區域內是不起作用的。

第二種

$("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實現復制文章自動添加版權的方法,代碼很簡單,有需要的朋友們可以參考學習。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved