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

时间:2017-06-17 09:16:16

标签: 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 的大型文本传递给函数时,我总是得到:

  

'复制文字命令失败'

基于CSV的示例文本传递到' copyTextToClipboard'无法在剪贴板中复制的功能 enter image description here

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

1 个答案:

答案 0 :(得分:1)

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

假设您不关心IE(请参阅caniuseES6 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

<小时/>

基本语法

  • 用反引号包裹字符串:`(键盘的左上角)而不是引号:&#34; &#39; < / KBD>

  • 使用${}代替"+ +"

  • 换行变量
  • 只需使用输入键而不是\n+

<小时/> 详细信息在演示

中进行了评论

Plunker

演示

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

button {
  float: right;
  margin-right: 10%
}
&#13;
<!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>
&#13;
&#13;
&#13;

辅助演示

从演示中粘贴文本

&#13;
&#13;
body {
  font: 400 13px/1.428 Consolas
}

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