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

相关: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;
    }
  };
})();

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

其他回答

将HTML输入中的文本复制到剪贴板:

函数myFunction(){/*获取文本字段*/var copyText=document.getElementById(“myInput”);/*选择文本字段*/copyText.select();/*复制文本字段中的文本*/document.execCommand(“复制”);/*提醒复制的文本*/alert(“Copied the text:”+copyText.value);}<!-- 文本字段--><input type=“text”value=“Hello Friend”id=“myInput”><!-- 用于复制文本-->的按钮<button onclick=“myFunction()”>复制文本</button>

注意:在Internet Explorer 9和更早版本中不支持document.execCommand()方法。

来源:W3Schools-将文本复制到剪贴板

我喜欢这个:

<input onclick="this.select();" type='text' value='copy me' />

如果用户不知道如何在操作系统中复制文本,那么他们很可能也不知道如何粘贴。因此,只需自动选择它,剩下的留给用户。

该代码于2021 5月测试。在Chrome、IE和Edge上工作下面的message参数是要复制的字符串值。

<script type="text/javascript">
    function copyToClipboard(message) {
        var textArea = document.createElement("textarea");
        textArea.value = message;
        textArea.style.opacity = "0"; 
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();


        try {
            var successful = document.execCommand('copy');
            var msg = successful ? 'successful' : 'unsuccessful';
            alert('Copying text command was ' + msg);
        } catch (err) {
            alert('Unable to copy value , error : ' + err.message);
        }

        document.body.removeChild(textArea);
    }

</script>

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

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

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

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

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

我用过clipboard.js。

我们可以在npm上获得:

npm install clipboard --save

还有Bower

bower install clipboard --save

新ClipboardJS(“#btn1”);document.querySelector(“#btn2”).addEventListener(“click”,()=>document.querySelector(“#btn1”).dataset.clipboardText=Math.random());<script src=“https://cdn.jsdelivr.net/npm/clipboard@2.0.8/dist/cclipboard.min.js“></script><button id=“btn1”数据剪贴板text=“要复制的文本位于此处”>复制到剪贴板</按钮><button id=“btn2”>单击此处更改数据剪贴板文本</button><br/><br/><input type=“text”placeholder=“粘贴到此处查看剪贴板”/>

更多用法和示例请访问https://zenorocha.github.io/clipboard.js/.