html 文本换行 \n 没有生效

  • 2022-07-14
  • 浏览 (2710)

文本中直接用 \n ,无法换行,因为 html 不识别 \n,如果只是单纯的用 replace 把 \n 换成 <br/>,只能变成普通的字符串,也还是无法换行。

解决方法有这么几种:

1. 用js处理

innerHTML = " ... " 或者 v-html 来把 <br/> 识别为 html node

2. 用html处理

在标签上套一个 <pre></pre>

3. 设置 css

white-space: pre-line; 或者 white-space:pre;

4. golang的处理方式

go 处理

import (
  "html/template"
)

....

template.HTML(htmlContent)

html 渲染

 {{.htmlContent}}

关于 white-space

white-space属性指定元素内的空白怎样处理。

属性定义及使用说明

默认值:	normal
继承:	yes
版本:	CSS1
JavaScript 语法:	object.style.whiteSpace="pre"

实例

//规定段落中的文本不进行换行:
p{
    white-space:nowrap;
}

属性值

值	         描述
normal	         默认。空白会被浏览器忽略。
pre	         空白会被浏览器保留。其行为方式类似 HTML 中的 <pre> 标签。
nowrap	         文本不会换行,文本会在在同一行上继续,直到遇到 <br> 标签为止。
pre-wrap	 保留空白符序列,但是正常地进行换行。
pre-line	 合并空白符序列,但是保留换行符。
inherit	         规定应该从父元素继承 white-space 属性的值。
0  赞