2017-03-15 101 views
5

我有一些非常基本的Javascript,只需按一下按鈕即可複製文本。我的問題是,它不保留換行符:複製按鈕保留換行符

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

我真的很喜歡的東西能夠被添加到上面的腳本,以避免使網站已經上了巨大的變化。

我已經看到了其他職位的東西,如:

post.innerHTML = post.innerHTML.replace(/\n/g, '<br>\n'); 

這在理論上將工作(我認爲),但我在使用Javascript吸。

有什麼建議嗎?

感謝

+1

什麼是元素類型?輸入或textarea? –

+0

[複製富文本到剪貼板使用js](http://stackoverflow.com/questions/23934656/javascript-copy-rich-text-contents-to-clipboard) –

回答

6

首先,在<input>元素不保留換行符。您可以改用<textarea>元素。由於您的HTML可能包含<br>元素而不是換行符,因此我還建議使用jQuery在每個<br>前加上\r\n

function copyToClipboard(element) { 
 
    var text = $(element).clone().find('br').prepend('\r\n').end().text() 
 
    element = $('<textarea>').appendTo('body').val(text).select() 
 
    document.execCommand('copy') 
 
    element.remove() 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p contenteditable="true">Type to edit <br> this text</p> 
 
<button onclick="copyToClipboard('p')">Copy to Clipboard</button>

+0

這很好,除了一件事...我在標籤之間的文字,似乎是導致它換行也。可以添加上面的內容,以便在發生以下情況時忽略:這是一些文本我希望全部出現在同一行上。 –

+0

在.find('br')'之前,插入'.find('ref.glowingtext')。remove()。end()' – gyre

+0

太棒了!非常感謝! –

0

我們已經適應了copyToClipboard功能得到它與我們的應用程序的工作。更改如下:

  • 將輸入更改爲textarea,以便傳遞換行符;
  • 將text()函數更改爲html(),以便傳遞HTML;
  • 使用正則表達式用換行符替換每個HTML br;
  • 使用另一個正則表達式去除剩餘的HTML。我們的 應用程序中的HTML應該只有<b><br>標籤,所以簡單的正則表達式應該可以工作,並且還可以處理可能存在的奇數標籤。

這裏是我們的適應功能,註釋也一起:

// Note: original replace used to strip HTML tags from https://stackoverflow.com/questions/5002111/javascript-how-to-strip-html-tags-from-string ReactiveRaven. 
// However, replaced closing (>|$) with > as I don't understand why the check for $ is there, as it implies that $ is part of an HTML tag. 
// Our requirement highly constrains the HTML, to mainly have <br> and <b> tags, so the general objection to parsing HTML with regex 
// as at https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags community wiki is not applicable. 
// BTW, that page is very entertaining! 
function copyToClipboard(element) 
{ 
    var $temp = $("<textarea>"); 
    $("body").append($temp); 
    var x = $(element).html().trim().replace(/<br>/g, '\n').replace(/<\/?[^>]+>/g, ''); 
    $temp.val(x).select(); 
    document.execCommand("copy"); 
    $temp.remove(); 
} 

順便說一句,如果有人知道爲什麼從引用頁面的正則表達式有(> | $),我們改爲>,我們會欣賞獲得理解,爲什麼我們需要刪除美元符號。