純JavaScript實現的解決方案:clipboard.jsjavascript
html部分:html
<p>點擊下面的按鈕將會觸發JavaScript將元素內容拷貝到剪貼板內。</p> <!-- 1. Define some markup --> <div> <input id="foo" type="text" value="你好clipboard,這裏(input)"> <button class="btn" data-clipboard-action="copy" data-clipboard-target="#foo">複製</button> </div> <!-- 1. Define some markup --> <div> <textarea id="bar">你好clipboard,這裏(textarea)!</textarea> <button class="btn" data-clipboard-action="cut" data-clipboard-target="#bar">剪切</button> </div> <!-- 1. Define some markup --> <div id="div-target">你好clipboard,這裏(div)!</div> <button class="btn" data-clipboard-action="copy" data-clipboard-target="#div-target">複製</button>
js部分:java
var clipboard = new Clipboard('.btn'); clipboard.on('success', function(e) { console.log(e); }); clipboard.on('error', function(e) { console.log(e); });
方法二:
<textarea cols="20" rows="10" id="biao1">用戶定義的代碼區域</textarea> <input type="button" onClick="copyUrl2()" value="點擊複製代碼" /> <script> function copyUrl2(){ var Url2=document.getElementById("biao1"); Url2.select(); // 選擇對象 document.execCommand("Copy"); // 執行瀏覽器複製命令 alert("已複製好,可貼粘。"); } </script>