首页 > 解决方案 > 使用 HTML 按钮将文本复制到剪贴板

问题描述

如何使用 javascript 将一些固定文本复制到剪贴板?

这是我的代码,它不起作用也许还有另一种方法,我不知道。

<button onclick="Copy()">Copy</button>
<script>
function Copy() {
document.execCommand("copy","Some text here");
}    
</script>

我想只使用按钮复制一些固定文本,所以我不必手动选择文本并复制它们。谢谢。

标签: javascripthtmlbuttonclipboard

解决方案


您可以尝试这种方法:

<script>
    function Copy() {
     var copyText = document.createElement("input");                  
     copyText.style="display:none";
     copyText.value  = "This is a paragraph";     
     document.body.appendChild(copyText); 
     copyText.select();
     copyText.setSelectionRange(0, 99999); /*For mobile devices*/
     document.execCommand("copy");
     alert("Copied the text: " + copyText.value);
   }
</script>

推荐阅读