我有一些非常基本的 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。
有什么建议吗?
谢谢
最佳答案
首先,<input>
元素不保留换行符。您可以使用 <textarea>
元素代替。由于您的 HTML 可能包含 <br>
元素而不是换行符,我还建议使用 jQuery 来添加 \r\n
在每个 <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>
关于javascript - 复制按钮保留换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42816349/