【问题标题】:How to copy text to the clipboard in Javascript?如何在Javascript中将文本复制到剪贴板?
【发布时间】:2012-04-05 07:33:42
【问题描述】:

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

【问题讨论】:

  • Stackoverflow 还不到四年... :-)
  • 但这个问题是在 2008 年提出的。=)
  • Pish tosh,2012 - 2008 = 4。每个人都知道这一点。 :P(开玩笑的,当然,你是对的。正在修复。)

标签: javascript clipboard


【解决方案1】:

此时最简单的做法是使用基于 Flash 的解决方案。 zeroclipboard 很常见(here 提供了一个很好的演练)。

浏览器供应商在过去几年中移除了对剪贴板的编程访问。 Safari/Chrome在WebKit一改后就失去了能力,而FireFox早就封杀了。只有 IE 仍然允许它,但它最初会在每个页面上显示一个警报。

【讨论】:

    【解决方案2】:

    试试这个

    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>

    【讨论】:

    • 你能解释一下你的答案吗? document.exe('copy') 已在引用的问题中使用
    猜你喜欢
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-19
    • 2021-10-30
    相关资源
    最近更新 更多