提问者:小点点

在HTML中呈现字符串并保留空格和换行符


我有一个MVC3应用程序,有一个细节页面。 作为其中的一部分,我有一个包含空格和新行的描述(从数据库中检索)。 当它呈现时,HTML将忽略新的行和空格。 我想对这些空格和新行进行编码,这样它们就不会被忽略了。

你是怎么做到的?

我尝试了html.encode,但它最终显示了编码(甚至不是在空格和新行上,而是在一些其他特殊字符上)


共3个答案

匿名用户

只需使用white-space:pre-wrap;对内容进行样式设置即可。

null

div {
    white-space: pre-wrap;
}
<div>
This is some text   with some extra spacing    and a
few newlines along with some trailing spaces        
     and five leading spaces thrown in
for                                              good
measure                                              
</div>

匿名用户

您是否尝试过使用

标记。

http://jsfiddle.net/nwera/

匿名用户

您可以使用white-space:pre-line来保留格式中的换行符。 不需要手动插入html元素。

.popover {
    white-space: pre-line;    
}

或者添加到html元素style=“white-space:pre-line;”