【问题标题】:Copy to clipboard with break line使用折线复制到剪贴板
【发布时间】:2018-02-12 23:22:26
【问题描述】:

我想将文本复制到剪贴板,但要换行。

问题:

如果您单击 sn-p 中的按钮并粘贴到记事本中,您将得到以下内容:

姓名:testSurname:testEmail:test@gmail.com地址:testCity:testCountry:null广告类别:testPlan:null网站:公司名称:testΜήνυμα:test

我想要什么:

如果可能,我希望在换行符中复制文本。和你复制的时候一样:

名称:测试
姓氏:考
电子邮件:test@gmail.com
...

function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
}

$( "#FailCopy" ).click(function() {
  alert("Well done! div #error-details has been copy to your clipboard, now paste it in the notepad or email!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!--text that i want to copy-->
    <h2>Div #error-details: the text I want to copy to clipboard:</h2>
    <er id="error-details">Name: test<br>Surname: test<br>Email: test@gmail.com<br>Address: test<br>City: test<br>Country: null<br>Ad Category: test<br>Plan: null<br>Website: <br>Company name: test<br>Μήνυμα: test</er>

    <br><br>
    
    <button id="FailCopy" type="button"  
     onclick="copyToClipboard('er#error-details')">Copy div to clipboard</button>

我还尝试通过在我的 div 中添加以下 css 规则:white-space:pre-wrap;,将 &lt;br&gt; 替换为 \n\r\n,但没有任何成功迹象。

【问题讨论】:

标签: javascript jquery copy clipboard


【解决方案1】:

您的代码有一些问题。

您的代码中的第一个问题是 $(element).text()jquery text() 将您的代码从 html 中剥离,包括 &lt;br&gt; 标记。所以剪贴板文本中没有换行符,因为所有 html 换行符都被删除了。所以没有什么可以替换的。

如果您想将&lt;br&gt; 保留为换行符,您需要使用.html() 并更手动地解析您的文本。

第二个问题是你使用了&lt;input&gt; 标签。 &lt;input&gt; 标签只有单行,所以你不能在那里有任何换行符。您需要使用&lt;textarea&gt; 进行转换。

最后一个问题同上,windows用户也应该使用\r\n

我用工作版本更新了你的 sn-p。

function copyToClipboard(element) {
  var $temp = $("<textarea>");
  var brRegex = /<br\s*[\/]?>/gi;
  $("body").append($temp);
  $temp.val($(element).html().replace(brRegex, "\r\n")).select();
  document.execCommand("copy");
  $temp.remove();
}

$( "#FailCopy" ).click(function() {
  alert("Well done! div #error-details has been copy to your clipboard, now paste it in the notepad or email!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!--text that i want to copy-->
    <h2>Div #error-details: the text I want to copy to clipboard:</h2>
    <er id="error-details">Name: test<br>Surname: test<br>Email: test@gmail.com<br>Address: test<br>City: test<br>Country: null<br>Ad Category: test<br>Plan: null<br>Website: <br>Company name: test<br>Μήνυμα: test</er>

    <br><br>
    
    <button id="FailCopy" type="button"  
     onclick="copyToClipboard('er#error-details')">Copy div to clipboard</button>

【讨论】:

    【解决方案2】:

    简单地将带换行符的字符串复制到剪贴板的非 jQuery 解决方案

    为清楚起见,请参考代码 cmets。

        function copyStringWithNewLineToClipBoard(stringWithNewLines){
    
            // Step 1: create a textarea element.
            // It is capable of holding linebreaks (newlines) unlike "input" element
            const mySmartTextarea = document.createElement('textarea');
            
            // Step 2: Store your string in innerHTML of mySmartTextarea element        
            mySmartTextarea.innerHTML = stringWithNewLines;
            
            // Step3: find an id element within the body to append your mySmartTextarea there temporarily
            const parentElement = document.getElementById('any-id-within-any-body-element');
            parentElement.appendChild(mySmartTextarea);
            
            // Step 4: Simulate selection of your text from mySmartTextarea programmatically 
            mySmartTextarea.select();
            
            // Step 5: simulate copy command (ctrl+c)
            // now your string with newlines should be copied to your clipboard 
            document.execCommand('copy');
    
            // Step 6: Now you can get rid of your "smart" textarea element
            parentElement.removeChild(mySmartTextarea);
            }
    

    现在只需复制粘贴此非详细方法并添加您自己的 cmets,以便将来管理您的代码的开发人员使用。 或者可能只是对此答案的参考。

    function copyStringWithNewLineToClipBoard(stringWithNewLines){
        const mySmartTextarea = document.createElement('textarea');
        mySmartTextarea.innerHTML = stringWithNewLines;
        const parentElement = document.body.appendChild(mySmartTextarea);
        mySmartTextarea.select();
        document.execCommand('copy');
        parentElement.removeChild(mySmartTextarea);
        }
    

    【讨论】:

    • 修复这个小错误时效果很好; parentElement.appendChild(textarea); => parentElement.appendChild(myFluffyTextarea);
    • 感谢您找到那个鬼鬼祟祟的 lil 虫子,它会立即将其粉碎。 :)
    • 所有的父元素部分对我来说都很难看为什么不只是:document.body.appendChild(mySmartTextarea);
    • 是的,这也完全可行。我不知道为什么我在 3 年前没有意识到这一点。
    【解决方案3】:

    有两点是错的:

    (1)根据text的jquery文档:

    .text() 方法的结果是一个包含所有匹配元素的组合文本的字符串。 (由于不同浏览器中 HTML 解析器的差异,返回的文本在换行符和其他空白处可能会有所不同。)

    还有他们的例子,

    <div class="demo-container">
        <div class="demo-box">Demonstration Box</div>
        <ul>
            <li>list item 1</li>
            <li>list <strong>item</strong> 2</li>
        </ul>
    </div>
    

    代码$( "div.demo-container" ).text() 将产生:

    Demonstration Box list item 1 list item 2

    所以只需使用html() 方法来获取innerHTML


    (2) &lt;input&gt; 标记删除换行符。请改用textarea。请参阅:this answer 了解更多信息。


    希望这个spinet可以工作。

    function copyToClipboard(element) {
      var $temp = $("<textarea>");
      $("body").append($temp);
      var html = $(element).html();
      html = html.replace(/<br>/g, "\n"); // or \r\n
      console.log(html);
      $temp.val(html).select();
      document.execCommand("copy");
      $temp.remove();
    }
    
    $( "#FailCopy" ).click(function() {
      alert("Well done! div #error-details has been copy to your clipboard, now paste it in the notepad or email!");
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    
    <!--text that i want to copy-->
    <h2>Div #error-details: the text I want to copy to clipboard:</h2>
    <er id="error-details">Name: test<br>Surname: test<br>Email: test@gmail.com<br>Address: test<br>City: test<br>Country: null<br>Ad Category: test<br>Plan: null<br>Website: <br>Company name: test<br>Μήνυμα: test</er>
    
    <br><br>
        
    <button id="FailCopy" type="button"  
         onclick="copyToClipboard('er#error-details')">Copy div to clipboard</button>

    【讨论】:

      【解决方案4】:

      您的代码可能运行良好,但记事本无法处理 Unix 的 \n 换行符,它只能处理 \r\n,这就是您看不到它们的原因。

      请下载更高级的编辑器(如 Notepad++,https://notepad-plus-plus.org)并尝试将其粘贴到那里。不仅如此,它还有许多其他非常酷的功能,如语法高亮、宏和插件,因此值得将它用于更多目的。

      如果您想让换行符在 MS 应用程序中工作,您需要在复制之前使用此行替换换行符:

      $temp = $temp.replace(/\n/g, "\r\n");
      

      要在 HTML 中打印,您需要将 \n 替换为
      ,如下所示:

      $temp = $temp.replace(/\n/g, "<br>");
      

      【讨论】:

      • 其实我想复制到微软的outlook(windows 10 app)。同样的事情没有换行符
      • 这就是我用javascript打印文本的方式:$("#error-details").html(Name: '+onoma+"&lt;br&gt;")+我应该把\r\n放在哪里?
      • 我在函数中添加了这一行,但我收到此错误"message": "Uncaught TypeError: $temp.replace is not a function" 如果这对您有用,请随时使用解决方案将我的 sn-p 复制到您的答案
      • 我在控制台中尝试了以下操作并且成功了:var $temp = "abcd\nabcd"; $temp = $temp.replace(/\n/g, "\r\n"); console.log($temp); // ==&gt; abcd\r\nabcd
      • 你的回答只解决了一小部分问题。
      猜你喜欢
      • 1970-01-01
      • 2019-07-18
      • 2010-11-17
      • 2011-09-15
      • 1970-01-01
      • 1970-01-01
      • 2015-08-27
      • 2015-08-31
      • 1970-01-01
      相关资源
      最近更新 更多