简体   繁体   English

从 textarea 复制到 div,保留换行符

[英]Copy from textarea to div, preserving linebreaks

I've got a <textarea> and a <div> (with a <p> inside).我有一个<textarea>和一个<div> (里面有一个<p> )。 When entering text into the area, the <p> gets updated with the content upon keyUp.在区域中输入文本时, <p>会根据 keyUp 的内容更新。

Is there a way to preserve linebreaks (new line) from the textarea and somehow get them to work like linebreaks in the div/p?有没有办法从 textarea 中保留换行符(新行)并以某种方式让它们像 div/p 中的换行符一样工作?

Replacing double "new line" with </p><p> , is that possible as well?</p><p>替换双“新行”,这也可能吗? This is close to what a wysiwyg would handle, but don't want that for this, which is a very small project.这接近于所见即所得的处理方式,但不希望这样做,这是一个非常小的项目。


This is what I've got so far.这是我到目前为止所得到的。

$(".box textarea").keyup(function () {
  var value = $(this).val();  
  $('.box p').text(value);
});

You probably want to add the CSS rule white-space: pre or white-space: pre-wrap to .box p .您可能希望将 CSS 规则white-space: prewhite-space: pre-wrap.box p This will display whitespace as-is.这将按原样显示空白。

You can simply do this:你可以简单地这样做:

$('.box textarea').keyup(function() {
    var value = $(this).val().replace(/\n/g, '<br/>');
    $(".box p").html(value);
});

This will replace all the line breaks \\n in your textarea element and replace them all with html <br/> tag, so that you can preserve the line breaks in your textarea inside <p> tag element also.这将替换textarea元素中的所有换行符\\n并将它们全部替换为 html <br/>标签,以便您也可以在<p>标签元素内保留 textarea 中的换行符。

Simple Demo Here:简单演示在这里:

 $('.box textarea').keyup(function() { $(".box p").html(this.value.replace(/\\n/g, '<br/>')); });
 textarea,p { width: 90%; height: 80px; } p { border: 1px solid #eee; padding: 5px; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="box"> <textarea></textarea> <br/> <p></p> </div>

If you can make changes to your css files, then you can also try the below solutions as suggested by @Explosion Pills .如果您可以对 css 文件进行更改,那么您还可以按照@Explosion Pills 的建议尝试以下解决方案。 Even though you will have to still use the jquery code here to add the textarea entered text to p tag on keyup event like:即使您仍然必须在此处使用 jquery 代码将textarea输入的文本添加到keyup事件的p标记中,例如:

 $('.box textarea').keyup(function() { $(".box p").html(this.value); // replace is not needed here });
 textarea,p { width: 90%; height: 80px; } p { border: 1px solid #eee; padding: 5px; white-space: pre; // <--- This is the important part }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="box"> <textarea></textarea> <br/> <p></p> </div>

Here's the simplest and safest pure jQuery solution:这是最简单、最安全的纯 jQuery 解决方案:

$(".box textarea").keyup(function () {
  var value = $(this).val();
  $('.box p').text(value).css('white-space', 'pre-wrap');
});

Of course, if you can add .box p { white-space: pre-wrap } to your static CSS styles, then you don't need to inject it with jQuery.当然,如果你可以将.box p { white-space: pre-wrap }到你的静态 CSS 样式中,那么你就不需要用 jQuery 注入它了。

(Also note that white-space: pre-wrap also causes multiple consecutive spaces to be preserved, and not to be collapsed into a single space. If you don't want that, but still want to preserve line breaks, use white-space: pre-line instead.) (另请注意, white-space: pre-wrap还会导致保留多个连续空格,而不是折叠成一个空格。如果您不希望那样,但仍想保留换行符,请使用white-space: pre-line代替white-space: pre-line 。)


Ps.附言。 You should never pass unescaped user input to .html() (as eg the currently accepted answer does), since doing so will cause mangled output if the input contains any HTML metacharacters like & or < , and can also open you to HTML injection and cross-site scripting (XSS) attacks if the input can ever be influenced by a malicious attacker.永远不应该将转义的用户输入传递给.html() (例如当前接受的答案),因为如果输入包含任何 HTML 元字符(如&< ),则这样做会导致错误的输出,并且还可以打开您进行 HTML 注入和如果输入可能受到恶意攻击者的影响,则跨站点脚本 (XSS) 攻击。

If you absolutely insist on not using the CSS white-space property in any form, you will need to first escape any HTML metacharacters in the input before adding <br> tags into it.如果您绝对坚持不以任何形式使用 CSS white-space属性,则需要先转义输入中的任何 HTML 元字符,然后再向其中添加<br>标签。 Probably the simplest and safest way to do that is to let the browser handle the escaping for you, eg like this:可能最简单和最安全的方法是让浏览器为您处理转义,例如:

$(".box textarea").keyup(function () {
  var value = $(this).val();
  $('.box div.output').text(value).html(function (index, html) {
    return '<p>' + html.replace(/[^\S\n]+\n/g, '\n').replace(/\n\n+/g, '</p><p>').replace(/\n/g, '<br>') + '</p>';
  });
});

This will first copy the input text into the target element using .text() (which automatically HTML-escapes it) and then modifies the resulting HTML code to remove trailing whitespace from lines, to collapse multiple consecutive linefeeds into paragraph breaks, and finally to replace single linefeeds with <br> tags.这将首先使用.text()将输入文本复制到目标元素中(它会自动对它进行 HTML 转义),然后修改生成的 HTML 代码以从行中删除尾随空格,将多个连续换行符折叠为分段符,最后将用<br>标签替换单个换行符。

(Note that, in order to allow multiple paragraphs in the output, the target element should really be a <div> , not a <p> element. Nesting one <p> element inside another is not valid HTML, and may not produce consistent results on different browsers.) (注意,为了允许输出中有多个段落,目标元素应该是一个<div> ,而不是一个<p>元素。将一个<p>元素嵌套在另一个元素中是无效的 HTML,并且可能不会产生一致的在不同浏览器上的结果。)

Use string.replace("\\n", "<br/>") to replace any line breaks in your text area to a new line in your page.使用string.replace("\\n", "<br/>")将文本区域中的任何换行符替换为页面中的新行。

JavaScript: JavaScript:

<script type="text/javascript">
function ta()
{
taValue = document.getElementById("ta").value;
taValue = taValue.replace("\n", "<br/>");
document.getElementById("tatext").innerHTML = taValue;
}
</script>

HTML: HTML:

<textarea id="ta" onkeyup="ta()"></textarea>
<div id="tatext"></div>

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

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