1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title>js复制</title> 7 <link href="../stylesheets/mdstyle.css" rel="stylesheet" type='text/css'/> 8 <style type="text/css"> 9 #cptext{ 10 color: red; 11 } 12 </style> 13 </head> 14 15 <body> 16 <article class="markdown-body"> 17 <p>第一种复制方式:复制input输入框中的内容</p> 18 <input type="text" id="website" value="http://yuedun.duapp.com" style="display:block;" /> 19 <button data-copytarget="#website" onclick="copy(event)">copy</button> 20 <pre> 21 <code class="javascript"> 22 function copy(e) { 23 // 搜索目标元素 24 var 25 t = e.target, 26 c = t.dataset.copytarget, 27 inp = (c ? document.querySelector(c) : null); 28 // 判断元素是否能被选中 29 if (inp) { 30 inp.style.display = 'block'; 31 // 选择文本 32 inp.select(); 33 try { 34 // 复制文本 35 document.execCommand('copy'); 36 inp.style.display = 'none'; 37 inp.blur(); 38 } catch (err) { 39 alert('please press Ctrl/Cmd+C to copy'); 40 } 41 } 42 } 43 </code> 44 </pre> 45 <hr> 46 <p>第二种复制方式:复制普通标签中的文本</p> 47 <p id="cptext">这是第二种方式复制的内容</p> 48 <button data-copytarget="#cptext" onclick="copy2(event)">copy</button> 49 <pre> 50 <code class="javascript"> 51 function copy2(e) { 52 var urlField = document.querySelector('#cptext'); 53 var range = document.createRange(); 54 urlField.style.display = "block"; 55 range.selectNode(urlField); 56 window.getSelection().addRange(range); 57 document.execCommand('copy'); 58 window.getSelection().removeAllRanges(); 59 urlField.style.display="none" 60 } 61 </code> 62 </pre> 63 </article> 64 <script> 65 function copy(e) { 66 // 搜索目标元素 67 var 68 t = e.target, 69 c = t.dataset.copytarget, 70 inp = (c ? document.querySelector(c) : null); 71 // 判断元素是否能被选中 72 if (inp) { 73 // inp.style.display = 'block'; 74 // 选择文本 75 inp.select(); 76 try { 77 // 复制文本 78 document.execCommand('copy'); 79 // inp.style.display = 'none'; 80 inp.blur(); 81 } catch (err) { 82 alert('please press Ctrl/Cmd+C to copy'); 83 } 84 } 85 } 86 function copy2(e) { 87 var urlField = document.querySelector('#cptext'); 88 var range = document.createRange(); 89 // urlField.style.display = "block"; 90 range.selectNode(urlField); 91 window.getSelection().addRange(range); 92 document.execCommand('copy'); 93 window.getSelection().removeAllRanges(); 94 // urlField.style.display="none" 95 } 96 </script> 97 </body> 98 99 </html>
本文来自 http://www.hopefully.wang/views/copy.html