繁体   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