如何将文本复制到剪贴板(多浏览器)?

相关:Trello如何访问用户的剪贴板?


当前回答

我把我认为最好的东西放在一起了。

使用cssText避免Internet Explorer中的异常,而不是直接使用样式。如果有选择,则恢复选择设置为只读,以便移动设备上不会出现键盘有一个适用于iOS的解决方案,因此它实际上可以像通常阻止execCommand一样工作。

这里是:

const copyToClipboard = (function initClipboardText() {
  const textarea = document.createElement('textarea');

  // Move it off-screen.
  textarea.style.cssText = 'position: absolute; left: -99999em';

  // Set to readonly to prevent mobile devices opening a keyboard when
  // text is .select()'ed.
  textarea.setAttribute('readonly', true);

  document.body.appendChild(textarea);

  return function setClipboardText(text) {
    textarea.value = text;

    // Check if there is any content selected previously.
    const selected = document.getSelection().rangeCount > 0 ?
      document.getSelection().getRangeAt(0) : false;

    // iOS Safari blocks programmatic execCommand copying normally, without this hack.
    // https://stackoverflow.com/questions/34045777/copy-to-clipboard-using-javascript-in-ios
    if (navigator.userAgent.match(/ipad|ipod|iphone/i)) {
      const editable = textarea.contentEditable;
      textarea.contentEditable = true;
      const range = document.createRange();
      range.selectNodeContents(textarea);
      const sel = window.getSelection();
      sel.removeAllRanges();
      sel.addRange(range);
      textarea.setSelectionRange(0, 999999);
      textarea.contentEditable = editable;
    }
    else {
      textarea.select();
    }

    try {
      const result = document.execCommand('copy');

      // Restore previous selection.
      if (selected) {
        document.getSelection().removeAllRanges();
        document.getSelection().addRange(selected);
      }

      return result;
    }
    catch (err) {
      console.error(err);
      return false;
    }
  };
})();

用法:复制到剪贴板(“部分文本”)

其他回答

我在从Excel(类似Excel)构建自定义网格编辑以及与Excel的兼容性方面遇到了同样的问题。我必须支持选择多个单元格、复制和粘贴。

解决方案:创建一个文本区域,您将在其中插入数据,供用户复制(当用户选择单元格时为我),设置焦点(例如,当用户按下Ctrl键时)并选择整个文本。

因此,当用户按下Ctrl+C时,他/她会复制他/她选择的单元格。测试后,只需将文本区域调整为一个像素(我没有测试它是否能在显示器上工作:无)。它在所有浏览器上都能很好地工作,并且对用户是透明的。

粘贴-你可以这样做(不同于你的目标)-关注文本区域并使用onpaste捕捉粘贴事件(在我的项目中,我使用单元格中的文本区域进行编辑)。

我不能粘贴一个例子(商业项目),但你明白了。

从网页读取和修改剪贴板会引发安全和隐私问题。然而,在Internet Explorer中,可以这样做。我找到了以下示例片段:

<script type=“text/javascript”>函数select_all(obj){var text_val=评估(对象);text_val.focus();text_val.select();r=text_val.createTextRange();if(!r.execCommand)return;//特征检测r.execCommand('copy');}</script><输入值=“http://www.sajithmr.com"onclick=“select_all(this)”name=“url”type=“text”/>

clipboard.js是一个小型的非Flash实用程序,允许将文本或HTML数据复制到剪贴板。它非常容易使用,只需包含.js并使用如下内容:

<button id='markup-copy'>Copy Button</button>

<script>
document.getElementById('markup-copy').addEventListener('click', function() {
  clipboard.copy({
    'text/plain': 'Markup text. Paste me into a rich text editor.',
    'text/html': '<i>here</i> is some <b>rich text</b>'
  }).then(
    function(){console.log('success'); },
    function(err){console.log('failure', err);
  });

});
</script>

clipboard.js也在GitHub上。

注意:现在已弃用此选项。迁移到此处。

我把我认为最好的东西放在一起了。

使用cssText避免Internet Explorer中的异常,而不是直接使用样式。如果有选择,则恢复选择设置为只读,以便移动设备上不会出现键盘有一个适用于iOS的解决方案,因此它实际上可以像通常阻止execCommand一样工作。

这里是:

const copyToClipboard = (function initClipboardText() {
  const textarea = document.createElement('textarea');

  // Move it off-screen.
  textarea.style.cssText = 'position: absolute; left: -99999em';

  // Set to readonly to prevent mobile devices opening a keyboard when
  // text is .select()'ed.
  textarea.setAttribute('readonly', true);

  document.body.appendChild(textarea);

  return function setClipboardText(text) {
    textarea.value = text;

    // Check if there is any content selected previously.
    const selected = document.getSelection().rangeCount > 0 ?
      document.getSelection().getRangeAt(0) : false;

    // iOS Safari blocks programmatic execCommand copying normally, without this hack.
    // https://stackoverflow.com/questions/34045777/copy-to-clipboard-using-javascript-in-ios
    if (navigator.userAgent.match(/ipad|ipod|iphone/i)) {
      const editable = textarea.contentEditable;
      textarea.contentEditable = true;
      const range = document.createRange();
      range.selectNodeContents(textarea);
      const sel = window.getSelection();
      sel.removeAllRanges();
      sel.addRange(range);
      textarea.setSelectionRange(0, 999999);
      textarea.contentEditable = editable;
    }
    else {
      textarea.select();
    }

    try {
      const result = document.execCommand('copy');

      // Restore previous selection.
      if (selected) {
        document.getSelection().removeAllRanges();
        document.getSelection().addRange(selected);
      }

      return result;
    }
    catch (err) {
      console.error(err);
      return false;
    }
  };
})();

用法:复制到剪贴板(“部分文本”)

自动复制到剪贴板可能很危险,因此大多数浏览器(Internet Explorer除外)都很难做到。就我个人而言,我使用以下简单技巧:

function copyToClipboard(text) {
  window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}

用户将看到提示框,其中已选择要复制的文本。现在,按下Ctrl+C和Enter键(关闭框)就足够了——瞧!

现在剪贴板复制操作是安全的,因为用户手动执行(但方式非常简单)。当然,它适用于所有浏览器。

<button id=“demo”onclick=“copyToClipboard(document.getElementById('demo').innerHTML)”>这是我要复制的内容</button><脚本>函数复制到剪贴板(文本){window.prpt(“复制到剪贴板:Ctrl+C,Enter”,文本);}</script>