有一需求,點擊按鈕要將某個值復制到剪貼板。
第一種,代碼如下:
1 <div cols="20" id="biao1">12345678</div> 2 <input type="button" onClick="copyUrl2()" value="點擊復制代碼" /> 3 4 function copyUrl2() { 5 var Url2 = document.getElementById("biao1").innerText; 6 var oInput = document.createElement("input"); 7 oInput.value = Url2; 8 document.body.appendChild(oInput); 9 oInput.select(); // 選擇對象 10 document.execCommand("Copy"); // 執行瀏覽器復制命令 11 oInput.className = "oInput"; 12 oInput.style.display = "none"; 13 alert("復制成功"); 14 }
第二種,代碼如下:
<textarea cols="20" rows="10" id="biao1">用戶定義的代碼區域</textarea>
<input type="button" onClick="copyUrl3()" value="點擊復制代碼" />
function copyUrl3() {
var Url2 = document.getElementById("biao1");
Url2.select(); // 選擇對象
document.execCommand("Copy"); // 執行瀏覽器復制命令
alert("已復制好,可貼粘。");
}
網上找到了這兩種寫法,經過實踐,切實可行。
