javascript 从 textarea 复制到 div,保留换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16165286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Copy from textarea to div, preserving linebreaks
提问by Xavio
I've got a <textarea>and a <div>(with a <p>inside).
When entering text into the area, the <p>gets updated with the content upon keyUp.
我有一个<textarea>和一个<div>(<p>里面有一个)。在该区域中输入文本时,<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? This is close to what a wysiwyg would handle, but don't want that for this, wich is a very small project.
用 替换双“新行” </p><p>,这也可能吗?这接近于所见即所得的处理方式,但不希望这样,这是一个非常小的项目。
This is what I've got so far.
这是我到目前为止所得到的。
$(".box textarea").keyup(function () {
var value = $(this).val();
$('.box p').text(value);
});
采纳答案by pala?н
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 \nin your textareaelement and replace them all with html <br/>tag, so that you can preserve the line breaks in your textarea inside <p>tag element also.
这将替换所有换行符\n在你的textarea元素,并与HTML全部更换<br/>标签,这样就可以在您的textarea的内部保留换行符<p>标签元素也。
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. Even though you will have to still use the jquery code here to add the textareaentered text to ptag on keyupevent like:
如果您可以对 css 文件进行更改,那么您还可以按照@Explosion Pills 的建议尝试以下解决方案。即使您仍然必须在此处使用 jquery 代码将textarea输入的文本p添加到keyup事件标记,例如:
$('.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>
回答by Explosion Pills
You probably want to add the CSS rule white-space: preor white-space: pre-wrapto .box p. This will display whitespace as-is.
您可能想要添加 CSS 规则white-space: pre或white-space: pre-wrap到.box p. 这将按原样显示空白。
回答by Ilmari Karonen
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-wrapalso 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-lineinstead.)
(另请注意,这white-space: pre-wrap也会导致保留多个连续空格,而不是折叠成一个空格。如果您不想要那样,但仍想保留换行符,请white-space: pre-line改用。)
Ps. You should neverpass unescaped user input to .html()(as e.g. 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-spaceproperty in any form, you will need to first escape any HTML metacharacters in the input before adding <br>tags into it. Probably the simplest and safest way to do that is to let the browser handle the escaping for you, e.g. like this:
如果您绝对坚持不white-space以任何形式使用 CSS属性,则需要先对输入中的任何 HTML 元字符进行转义,然后再向其中添加<br>标签。可能最简单和最安全的方法是让浏览器为您处理转义,例如:
$(".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 firstcopy 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,并且在不同的浏览器上可能不会产生一致的结果。)
回答by Savv
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>

