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

Hov*_*yan 6 html javascript clipboard

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

  function GeeksForGeeks() {
            var copyGfGText = document.getElementById("GfGInput");
            copyGfGText.select();

            document.execCommand("copy");

            alert("Copied the text: " + copyGfGText.value);
          }
Run Code Online (Sandbox Code Playgroud)
  <input type="text" value="GeeksForGeeks" id="GfGInput">

         <!-- The button used to copy the text -->
         <button onclick="GeeksForGeeks()">Copy text</button>
Run Code Online (Sandbox Code Playgroud)

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

let text = "copy this text to the clipboard";
Run Code Online (Sandbox Code Playgroud)

mw5*_*509 23

你应该能够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);
}
Run Code Online (Sandbox Code Playgroud)
<button onclick="CopyMe('The text here will be copied')">Copy text</button>
Run Code Online (Sandbox Code Playgroud)

让我知道这有什么帮助。

=============== 更新 - 2023 年 3 月 ===========

execCommand 方法可能不适用于所有浏览器,因此现在更好的方法是:

function copyToClipboard(text) {
  navigator.clipboard.writeText(text)
.then(() => {
  console.log(`Copied text to clipboard: ${text}`);
  alert(`Copied text to clipboard: ${text}`);
})
.catch((error) => {
  console.error(`Could not copy text: ${error}`);
});
}
Run Code Online (Sandbox Code Playgroud)
<button onclick="copyToClipboard('The text here will be copied')">Copy text</button>
Run Code Online (Sandbox Code Playgroud)

这是执行相同操作的更好、更干净的方法,但如果您正在使用的网站具有内容安全策略 (CSP) 或其他阻止访问剪贴板的安全设置,您将收到错误 ( https://sites.google .com/a/chromium.org/dev/Home/chromium-security/deprecating-permissions-in-cross-origin-iframes)。

  • 这非常有效。注意:如果文本中有换行符,请使用 document.createElement("textarea");`。 (2认同)