【问题标题】:Copy Button Preserving Line Breaks复制按钮保留换行符
【发布时间】:2017-08-06 13:56:28
【问题描述】:

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

有什么建议吗?

谢谢

【问题讨论】:

标签: javascript


【解决方案1】:

首先,&lt;input&gt; 元素不保留换行符。您可以改用&lt;textarea&gt; 元素。由于您的 HTML 可能包含 &lt;br&gt; 元素而不是换行符,我还建议使用 jQuery 在每个 &lt;br&gt; 之前添加 \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>

【讨论】:

  • 这很好用,除了一件事......我在文本之间有标签,似乎也导致它换行。是否可以在上面添加一些内容以在发生以下情况时忽略:这是一些我希望出现在同一行的文本 .
  • .find('br')之前,插入.find('ref.glowingtext').remove().end()
  • 太棒了!非常感谢!
【解决方案2】:

我们已经调整了 copyToClipboard 函数以使其与我们的应用程序一起工作。变化如下:

  • 将输入更改为 textarea 以便通过换行符;
  • 将 text() 函数更改为 html() 以便传递 HTML;
  • 使用正则表达式将每个 HTML br 替换为换行符;
  • 使用另一个正则表达式去除剩余的 HTML。我们的 HTML 应用程序应该只有 &lt;b&gt;&lt;br&gt; 标签,所以简单的正则表达式应该可以工作,并且还可以处理可能存在的奇数标签。

这是我们改编的函数以及 cmets:

// 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();
}

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

【讨论】:

    猜你喜欢
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 2013-04-02
    • 2021-04-28
    • 2018-11-22
    相关资源
    最近更新 更多