复制按钮保留换行符

hea*_*igg 11 javascript

我有一些非常基本的Javascript,只需按一下按钮即可复制文本.我的问题是它不会保留换行符:

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

我真的希望能够添加到上面的脚本中,以避免在网站上进行大的更改.

我在其他帖子上看过的内容如下:

post.innerHTML = post.innerHTML.replace(/\n/g, '<br>\n');
Run Code Online (Sandbox Code Playgroud)

这在理论上是可行的(我认为),但我吮吸Javascript.

有什么建议?

谢谢

gyr*_*yre 15

首先,<input>元素不保留换行符.您可以使用该<textarea>元素.由于您的HTML可能包含<br>元素而不是换行符,我还建议\r\n在每个之前使用jQuery进行前置<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()
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)