繁体   English   中英

将文本复制到剪贴板而不使用任何输入

[英]Copy the text to the Clipboard without using any input

刚刚在web中看到很多文章,想找到将文本复制到剪贴板的解决方案。 但是每个教程都用输入示例进行解释。

 function GeeksForGeeks() { var copyGfGText = document.getElementById("GfGInput"); copyGfGText.select(); document.execCommand("copy"); alert("Copied the text: " + copyGfGText.value); }
 <input type="text" value="GeeksForGeeks" id="GfGInput"> <!-- The button used to copy the text --> <button onclick="GeeksForGeeks()">Copy text</button>

但我只需要复制一个简单的文本。 有没有办法将简单字符串从变量复制到剪贴板? 示例`

let text = "copy this text to the clipboard";

您应该可以使用document.createElement(); 像这样;

 function CopyMe(TextToCopy) { var TempText = document.createElement("input"); TempText.value = TextToCopy; document.body.appendChild(TempText); TempText.select(); document.execCommand("copy"); document.body.removeChild(TempText); alert("Copied the text: " + TempText.value); }
 <button onclick="CopyMe('The text here will be copied')">Copy text</button>

让我知道这有什么帮助。

似乎当前的解决方案只需要使用在当前 EDGE 中也可以使用的“navigator.clipboard”。

 navigator.clipboard.writeText('my text to be written to the clipboard ...')
                                                .then(() => { alert('Copy successful'); })
                                                .catch((error) => { alert(`Copy failed! ${error}`); });

https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/write

Fluchaa 要求使用改进的 Sarah 代码:

$("#myButton").click(function() {
    this.focus();
    navigator.clipboard.writeText("MY PLAIN TEXT")
                                   .then(() => { alert("Copy successful"); })
                                   .catch((error) => { alert(`Copy failed! ${error}`); });
});

暂无
暂无

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

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