標籤:window play href 複製 ecc ddr value and 文本
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 var25 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 var68 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
JS實現複製功能