繁体   English   中英

复制按钮保留换行符

[英]Copy Button Preserving Line Breaks

我有一些非常基本的 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 在每个<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>

我们已经调整了 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();
}

顺便说一句,如果有人知道为什么引用页面中的正则表达式的 (>|$) 是我们更改为 > 的,我们将不胜感激地了解为什么需要我们删除的美元符号。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM