复制按钮保留换行符 [英] Copy Button Preserving Line Breaks
问题描述
我有一些非常基本的Javascript,只需按一下按钮即可复制文本。我的问题是它不会保留换行符:
I have some very basic Javascript that copies text upon the push of a button. My problem is that it doesnt preserve line breaks:
<script>
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
</script>
我真的想要能够添加到上面的脚本中以避免做出巨大的改变在网站上已经。
I'd really like something to be able to be added to the above script to avoid making huge changes on the site already.
我在其他帖子上看过的内容如下:
I've seen things on other posts such as:
post.innerHTML = post.innerHTML.replace(/\n/g, '<br>\n');
这在理论上是可行的(我认为),但我对Javascript感到厌烦。
which in theory would work (i think) but I suck at Javascript.
有任何建议吗?
谢谢
推荐答案
首先,< input>
元素不会保留换行符。您可以使用< textarea>
元素。由于您的HTML可能包含< br>
元素而不是换行符,我还建议使用jQuery来预置 \\\\ n
在每个< br>
之前。
First off, the <input>
element doesn't preserve line breaks. You can use the <textarea>
element instead. Since your HTML may contain <br>
elements instead of line break characters, I would also suggest using jQuery to prepend \r\n
before each <br>
.
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>
这篇关于复制按钮保留换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!