簡體   English   中英

document.execCommand("copy") 不適用於所有瀏覽器

[英]document.execCommand("copy") not working on all browser

<input id="test" value="Test" disabled />
<a onclick="copy()">Button</a>

function copy(){
   var text = document.getElementById("test");

   text.select();
   document.execCommand("copy");

   console.log("Copied the text: " + text.value);
}

我有上述功能來復制我的副本。 但它不起作用。

您的代碼存在一些問題:

  • 輸入上的disable屬性實際上必須被disabled
  • 當您在輸入上設置disabled時,您無法選擇其文本以復制它,因此您可能希望在這種情況下使用readonly或通過navigator.clipboard.writeText(text.value)手動設置text.value
  • 剪貼板 API 並非在所有瀏覽器中都可用,請參閱https://caniuse.com/#feat=clipboard 長期以來,人們使用 Flash 進行剪貼板操作,但隨着瀏覽器中刪除 Flash 支持,沒有任何選擇余地。 但是,有像clipboard.js這樣的庫可以簡化跨受支持瀏覽器的剪貼板操作。

 function copy(){ var text = document.getElementById("test"); // set arbitrary value instead of current selection // to clipboard to make it work with a disabled input as well navigator.clipboard.writeText(text.value); // text.select(); //document.execCommand("copy"); console.log("Copied the text: " + text.value); } function copy2(){ var text = document.getElementById("test2"); text.select(); document.execCommand("copy"); console.log("Copied the text: " + text.value); }
 <input id="test" value="Test" disabled /> <a onclick="copy()">Button</a> <hr> <h3>using <code>document.execCommand("copy")</code></h3> <input id="test2" value="Test2" readonly /> <a onclick="copy2()">Button</a>

你可以使用這個clipboard.js庫。 它有很好的瀏覽器支持。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM