关于Javascript中的复制

在做项目时有一个需求,是需要复制内容到剪切板,因为有众多浏览器,所以要兼容性很重要

1、最简单的copy,只能在IE下使用

 1 <script type="text/javascript">
 2   function copy(){
 3         window.clipboardData.setData("text",document.getElementById("name").value);
 4         alert("The text is on the clipboard, try to paste it!");
 5     }
 6 </script>
7 <head> 8 <script type="text/javascript"> 9 function CopyToClipboard () { 10 var input = document.getElementById ("toClipboard"); 11 var textToClipboard = input.value; 12 13 var success = true; 14 if (window.clipboardData) { // Internet Explorer 15 window.clipboardData.setData ("Text", textToClipboard); 16 } 17 else { 18   // create a temporary element for the execCommand method 19   var forExecElement = CreateElementForExecCommand (textToClipboard); 20 21 /* Select the contents of the element 22 (the execCommand for 'copy' method works on the selection) */ 23 SelectContent (forExecElement); 24 25 var supported = true; 26 27 // UniversalXPConnect privilege is required for clipboard access in Firefox 28 try { 29 if (window.netscape && netscape.security) { 30 netscape.security.PrivilegeManager.enablePrivilege ("UniversalXPConnect"); 31 } 32 33   // Copy the selected content to the clipboard 34 // Works in Firefox and in Safari before version 5 35 success = document.execCommand ("copy", false, null); 36 } 37 catch (e) { 38 success = false; 39 } 40 41 // remove the temporary element 42 document.body.removeChild (forExecElement); 43 } 44 45 if (success) { 46 alert ("The text is on the clipboard, try to paste it!"); 47 } 48 else { 49 alert ("Your browser doesn't allow clipboard access!"); 50 } 51 } 52 53 function CreateElementForExecCommand (textToClipboard) { 54 var forExecElement = document.createElement ("div"); 55 // place outside the visible area 56 forExecElement.style.position = "absolute"; 57 forExecElement.style.left = "-10000px"; 58 forExecElement.style.top = "-10000px"; 59 // write the necessary text into the element and append to the document 60 forExecElement.textContent = textToClipboard; 61 document.body.appendChild (forExecElement); 62 // the contentEditable mode is necessary for the execCommand method in Firefox 63 forExecElement.contentEditable = true; //可以注释掉以免iPhone设备上弹出输入法,扰乱视线 64 65 return forExecElement; 66 } 67 68 function SelectContent (element) { 69 // first create a range 70 var rangeToSelect = document.createRange (); 71 rangeToSelect.selectNodeContents (element); 72 73 // select the contents 74 var selection = window.getSelection (); 75 selection.removeAllRanges (); 76 selection.addRange (rangeToSelect); 77 } 78 </script> 79 </head> 80 <body> 81 <input id="toClipboard" value="text to clipboard"/> 82 <button onclick='CopyToClipboard ()'>Copy text to clipboard</button> 83 </body>

 

posted on 2016-11-22 19:34  晓小东  阅读(253)  评论(0)    收藏  举报

导航