Html div 中文本中的新行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11423300/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 01:34:13  来源:igfitidea点击:

New lines in text within a div

htmltextarea

提问by domoindal

I have a little issue related to when I place a text loaded via ajax call.

当我放置通过 ajax 调用加载的文本时,我有一个小问题。

I take the contect from a textarea and store it in my database and when I want to show the text in a div, it doesn't respect the new lines, so all the text is continuous.

我从 textarea 中获取 contect 并将其存储在我的数据库中,当我想在 div 中显示文本时,它不尊重新行,因此所有文本都是连续的。

The following code show a small example:

以下代码显示了一个小示例:

$(function() {
    $('.buttonA').click(function() {
        $('.message').html($('textarea[name="mensaje"]').val());
    });
});
.message {
    width:300px;
    height:200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<textarea name="mensaje" class="new_message_textarea" placeholder="enter message..."></textarea>
<button class="buttonA">Enter</button>
<div class="message"></div>

If you type some text with some new lines, once you click on the button, the text is show into the div and will see that new lines are not show.

如果你输入一些带有新行的文本,一旦你点击按钮,文本就会显示到 div 中,并且会看到没有显示新行。

How can I solve this?

我该如何解决这个问题?

采纳答案by JoeCortopassi

Newline characters don't do any thing to html rendering. Change this in your js:

换行符对 html 渲染没有任何作用。在你的 js 中改变这个:

$('.message').html($('textarea[name="mensaje"]').val());

...to this:

...到这个:

$('.message').html($('textarea[name="mensaje"]').val().replace(/\n/g, "<br />"));

...and it will replace your newlines with a proper html line break

...它将用适当的 html 换行符替换您的换行符

回答by Chris.Zou

I think a better way to achieve this is to add

我认为实现这一目标的更好方法是添加

white-space: pre

or

或者

white-space: pre-wrap

style to your div. see HTML - Newline char in DIV content editable?

样式到您的 div。请参阅HTML - DIV 内容中的换行符是否可编辑?

回答by Cong Lance

Add this to the CSS:

将此添加到 CSS:

white-space: pre-line