點選按鈕複製到剪貼簿 js
阿新 • • 發佈:2019-01-01
<span style="font-family: Arial, Helvetica, sans-serif;">案例一:</span>
</pre><pre code_snippet_id="1755225" snippet_file_name="blog_20160711_1_4917192" name="code" class="html"><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Document</title> </head> <body> <script data-cfhash='f9e31' type="text/javascript"> function jsCopy(){ var e=document.getElementById("copy-num");//物件是copy-num1 e.select(); //選擇物件 document.execCommand("Copy"); //執行瀏覽器複製命令 alert("複製成功"); } /* <![CDATA[ */ ! function() { try { var t = "currentScript" in document ? document.currentScript: function() { for (var t = document.getElementsByTagName("script"), e = t.length; e--;) if (t[e].getAttribute("data-cfhash")) return t[e] } (); if (t && t.previousSibling) { var e, r, n, i, c = t.previousSibling, a = c.getAttribute("data-cfemail"); if (a) { for (e = "", r = parseInt(a.substr(0, 2), 16), n = 2; a.length - n; n += 2) i = parseInt(a.substr(n, 2), 16) ^ r, e += String.fromCharCode(i); e = document.createTextNode(e), c.parentNode.replaceChild(e, c) } t.parentNode.removeChild(t); } } catch(u) {} } () /* ]]> */ </script> <div class="nav navbar-top-links navbar-right"> <li>推廣連結:</li> <li><input id="copy-num" class="form-control" type="text" value="" style="max-width:100px;display:inline-block;color: #999; margin-top:12px"></li> <li><button onClick="jsCopy()" type="button" class="btn btn-sm">複製</button></li> </div> </body> </html>
案例二:
<html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Zero Clipboard Test</title> </script> </head> <body> <script type="text/javascript"> function jsCopy(){ var e=document.getElementById("contents");//物件是contents e.select(); //選擇物件 tag=document.execCommand("Copy"); //執行瀏覽器複製命令 if(tag){ alert('複製內容成功'); } } </script> <textarea id="contents" cols="40" rows="5"></textarea> <br /> <input type="button" onClick="jsCopy();" value="複製" /> </body> </html>
以上都可以執行,親自測試!