繁体   English   中英

如何在 Javascript 中将文本复制到剪贴板?

[英]How to copy text to the clipboard in Javascript?

我想知道是否有任何方法可以将文本复制到剪贴板。 我很清楚这个答案,但它现在已经三年多了。 从那以后有什么改变吗?

此时最简单的方法是使用基于 Flash 的解决方案。 zeroclipboard是常见的(这里有一个很好的演练)。

浏览器供应商在过去几年中取消了对剪贴板的编程访问。 Safari/Chrome 在 WebKit 改版后失去了能力,FireFox 长时间屏蔽。 只有 IE 仍然允许它,但是它最初在每个页面上显示一个警报。

尝试这个

 function myFunc() { /* Get the text field */ let copyText = document.getElementById("myInput"); /* Select the text field */ copyText.select(); /* Copy the text inside the text field */ document.execCommand("copy"); /* Alert the copied text */ alert("Copied the text: " + copyText.value); }
 input { display: inline-block; padding: .60rem; font-size: 1rem; color: #495057; background-color: #f1f1f1; border: 1px solid #ced4da; border-radius: .25rem; } button { display: inline-block; font-weight: 400; color: #ffffff; cursor: pointer; text-align: center; user-select: none; background-color: #007bff; border: 1px solid transparent; padding: .375rem .75rem; font-size: 1rem; line-height: 1.5; border-radius: .25rem; outline: 0; }
 <!-- The text field --> <input type="text" id="myInput" value="Some Random Text"> <!-- The button used to copy the text --> <button type="button" onclick="myFunc()">Copy</button>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM