我刚刚在网上看到很多文章,以找到一种将文本复制到剪贴板的解决方案。但是每个教程都用输入示例进行解释。
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";
答案 0 :(得分:2)
您应该可以像这样用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>
让我知道这有什么帮助。
答案 1 :(得分:1)
看来目前的解决方案只需要使用 "navigator.clipboard" 也适用于当前的 EDGE。
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