javascript - 无法将文本复制到剪贴板 - JavaScript

标签 javascript jquery

我正在尝试将基于 csv 的数据(来自 SlickGrid)复制到系统剪贴板中。 对于小块数据,它工作正常,但是当我有大量数据时,它无法复制到系统剪贴板。

这是用于执行复制的代码:

copyTextToClipboard: function (text) {
    var textArea = document.createElement('textarea');

    // Hide textArea
    textArea.style.position = 'fixed';
    textArea.style.top = 0;
    textArea.style.left = 0;
    textArea.style.width = '2em';
    textArea.style.height = '2em';
    textArea.style.padding = 0;
    textArea.style.border = 'none';
    textArea.style.outline = 'none';
    textArea.style.boxShadow = 'none';
    textArea.style.background = 'transparent';

    textArea.value = text;
    document.body.appendChild(textArea);
    textArea.select();

    try {
        var successful = document.execCommand('copy');
        var msg = successful ? 'successful' : 'unsuccessful';
        console.log('Copying text command was ' + msg);
    } catch (err) {
        alert('Oops, unable to copy to clipboard');
    }

    document.body.removeChild(textArea);
}

当我将基于 csv 的大型文本传递给函数时,我总是得到:

'Copying text command was unsuccessful'

基于 CSV 的示例文本传递到“copyTextToClipboard”函数,但无法复制到剪贴板 enter image description here

这里的另一件有趣的事情是,当我使用开发工具并跨过每一行时,它会正确地将相同的数据复制到剪贴板中。

最佳答案

它正常失败并且在控制台中给出部分结果的原因是因为输入不止一行。您的函数被设计为接受没有换行符的普通字符串。我假设在 ES6 之前,您必须手动或以编程方式插入带有反斜杠 \n+ 的换行符。

假设您不关心 IE(请参阅 caniuse )ES6 Template Literals将不起眼的弦乐提升到一个全新的水平。以下演示中使用的功能是:

  // Conventional String
   var str = "These   words   are   3   spaces   apart"; 

  // Template Literal
   var tl = `These   words   are   3   spaces   apart`
   var x = 123;

  // Conventional String
   var str = "Height: " + x + "px";

  // Template Literal
   var tl = `Height: ${x}px`;
 // Conventional String
   var str = "\n+"
             "Multiple\n+"
             "lines\n";

 // Template Literal
   var tl = `
            Multiple
            lines


基本语法

  • 用反引号括起字符串:`(键盘左上角)而不是引号:"'

  • ${} 代替 "++" 包裹变量

  • 只需使用enter键而不是\n+

<小时/> 详情请见demo

Plunker

演示

textarea {
  width: 90%;
  min-height: 100px;
  margin: 10px;
  border: 2px solid black;
  font: inherit;
}

button {
  float: right;
  margin-right: 10%
}
<!DOCTYPE html>
<html>

<head>
  <style>
    body {
      font: 400 13px/1.428 Consolas;
    }
    /* This is just to make the console
    || display data that needs no horizontal 
    || scrolling to read.
    */
    
    .as-console {
      word-break: break-word;
    }
    
    button {
      margin-left: 18ch;
    }
  </style>
</head>

<body>
  <ol>
    <li>Enter text with line breaks.✎</li>
    <li>Click the <kbd>DONE</kbd> button</li>
    <li>Next do one of the following:
      <ul>
        <li>Open a text editor (like Notepad)</li>
        <div>OR</div>
        <li>Go to the auxiliary demo on this answer</li>
      </ul>
      <li>Paste into the text editor or the aux demo</li>
  </ol>
  <p>✎ or you can use a <a href='https://pastebin.com/VZ6Vk4py' target='_blank'>
delimited text file (CSV) of 26 columns and 1000 rows
</a> (right click and open new tab.)</p>

  <textarea id='TA'></textarea>
  <br/>
  <button>DONE</button>
  <br/>

  <script>
    // Reference the <textarea>
    var TA = document.getElementById('TA');

    /* Register #TA to the change event
    || After the user has typed in #TA
    || and then clicks elsewhere 
    || (like the inert <button>)... 
    */
    TA.addEventListener('change', function(e) {

      /* ... the callback function is invoked and
      || the value of the changed element
      || (i.e. e.target = #TA) is passed thru.
      */
      copyTextToClipboard(e.target.value);
    });

    // Define callback function
    function copyTextToClipboard(text) {

      // Create a <textarea>
      var textArea = document.createElement('textarea');
      // Hide new <textarea>
      textArea.style.opacity = 0;

      // Append new <textarea> to the <form>
      document.body.appendChild(textArea);

      /* Wrap the data in backticks:` 
      || (key is top left corner of keyboard)
      || and the variable of data in a dollar
      || sign and curly brackets: ${}
      || The data (a string), is now an 
      || ES6 template literal.
      */
      var str = `${text}`;

      // Assign the new <textArea> value to str
      textArea.value = str;

      /* .select() method gets the content of
      || new <textarea>
      */
      textArea.select();

      /* copy the selected text to the OS
      || clipboard.
      */
      document.execCommand('copy');

      console.log(str);
    }
  </script>
</body>

</html>

辅助演示

在此处粘贴演示中的文本

body {
  font: 400 13px/1.428 Consolas
}

textarea {
  width: 90%;
  min-height: 250px;
  margin: 10px;
  border: 2px solid black;
  font: inherit;
}
<textarea placeholder='Paste text in this textarea'></textarea>

关于javascript - 无法将文本复制到剪贴板 - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44602815/

相关文章:

javascript - SO是如何动态获取它的Tag的呢?

javascript - 如何检测可编辑多边形何时被修改?

javascript - 你会推荐什么客户端javascript缓存库?

javascript - 在 JavaScript 中创建数组集合?

javascript - jQuery 从 HTML block 中删除错误标签

javascript - 把JS应用到工作中

jquery - Codekit Uglify.js 'Unexpected token punc' 错误

javascript - 使用 javascript 或 jquery 禁用鼠标双击

javascript - 使用 javascript 执行计算的两个八进制数

javascript - jQuery : Removing parent tag not the child of that parent