簡體   English   中英

如何在JS中復制文本和換行符

[英]How to copy text and newlines in JS

我有一些這樣的文字

text = 'line 1' + "\r\n";
text+= 'line 2' + "\r\n";
text+= 'line 3' + "\r\n";

我使用此功能將其復制到剪貼板

function copyToClipboard(text)
{

    var copyElement = document.createElement("span");
    copyElement.appendChild(document.createTextNode(text));
    copyElement.id = 'tempCopyToClipboard';
    angular.element(document.body.append(copyElement));

    // select the text
    var range = document.createRange();
    range.selectNode(copyElement);
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);

    // copy & cleanup
    document.execCommand('copy');
    window.getSelection().removeAllRanges();
    copyElement.remove();
}

如何在不丟失換行符的情況下將其復制到剪貼板?

當我在函數中定義文本時,它似乎對我有用。 您確定新行已按預期傳遞到函數中嗎?

 function copyToClipboard() { var text = 'line 1' + "\\r\\n"; text+= 'line 2' + "\\r\\n"; text+= 'line 3' + "\\r\\n"; var copyElement = document.createElement("span"); copyElement.appendChild(document.createTextNode(text)); copyElement.id = 'tempCopyToClipboard'; angular.element(document.body.append(copyElement)); // select the text var range = document.createRange(); range.selectNode(copyElement); window.getSelection().removeAllRanges(); window.getSelection().addRange(range); // copy & cleanup document.execCommand('copy'); window.getSelection().removeAllRanges(); copyElement.remove(); } 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <button type="button" onclick="copyToClipboard()">Copy text to clipboard</button> 

抱歉,我很抱歉復制了此代碼段,但我只是意識到我應該使用文本區域而不是跨度。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM