2017-03-15 65 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(); 
} 

顺便说一句,如果有人知道为什么从引用页面的正则表达式有(> | $),我们改为>,我们会欣赏获得理解,为什么我们需要删除美元符号。