Swi*_*ger 44 javascript vue.js
我正在创建一个便笺应用程序,用户可以通过在textarea中输入多行文本来添加便笺.当我在Firebase中保存笔记时,它将使用我想要显示的换行符(\n)保存.
因此,我写了一个过滤器来替换这些字符<br />并且效果很好.
虽然,现在我需要使用渲染我的数据{{{note.content}}},用户可以注入将要执行的HTML,CSS和JS.
我应该使用类似DOMPurify的内容来验证内容,还是有办法安全地呈现换行符?
Krz*_*iek 109
正如@shelvacu所说,<pre>html标签保留了空格.
但是使用它有一个严重的缺点:标签本身从项目中使用的CSS框架(例如Bootstrap)继承了大量不必要的样式.
要保留空格并避免继承任何不必要的样式,请使用:
<span style="white-space: pre;">Some whitespaced content</span>
Run Code Online (Sandbox Code Playgroud)
什么会像<pre>标签那样行事.
请注意,white-space: pre如果您希望在必要时使用其他换行符,那么它仍然是"原样" - white-space: pre-wrap.
请参阅:w3schools.com CSS white-space Property
She*_*acu 39
pre元素中.一个<pre>元素将预先在它服务的空白,如:
This is followed by a newline,
not that you can tell
<br />
<br />
<pre>You can see the newline after me!
Woohoo!</pre>
Run Code Online (Sandbox Code Playgroud)
将导致:
This is followed by a newline, not that you can tell
You can see the newline after me!
Woohoo!
Run Code Online (Sandbox Code Playgroud)
这样,您就不需要对换行进行任何过滤.
Swi*_*ger 29
在实际描述我的问题之后,我明白了使用预格式文本的预标签.此标记将尊重'\ t \n'个字符并正确显示文本!虽然句子不会自动破坏并溢出宽度.使用一些CSS,我能够获得与其他元素相同的行为.
HTML:
{{note.content}}
CSS:
.note pre {
white-space: pre-wrap;
word-wrap: break-word;
font-family: inherit;
}
Run Code Online (Sandbox Code Playgroud)
Tom*_*rae 15
我并不是真正的粉丝pre(除了调试!)所以这里是另一种使用v-for. 这使得调整格式变得更容易(例如,也许您想使用列表或其他不是spanand的东西br)
<span
v-for="(line,lineNumber) of stringWithNewlines.split('\n')"
v-bind:key="lineNumber" >
{{ line }}<br/>
</span>
Run Code Online (Sandbox Code Playgroud)
Shi*_*127 12
使用white-space: pre-line;CSS属性。
正如在Mozzila Doc中为pre-line价值所写:
空白序列被折叠。在换行符处的行被断开
<br>,并在必要时填充行框。
Ada*_*cha 10
希望这会为新访客增加价值。
I am big line with lots and lots of text which would make me not fit.
Line two ?
Line three
Run Code Online (Sandbox Code Playgroud)
<span style="white-space: pre-line">Your Content</span>
Run Code Online (Sandbox Code Playgroud)
<span style="white-space: pre">Your Content</span>
Run Code Online (Sandbox Code Playgroud)
参考及更多详情:https : //css-tricks.com/almanac/properties/w/whitespace
我可以使用反引号 (`) 使其工作
<pre>{{textRenderedAsItIs}}</pre>
Run Code Online (Sandbox Code Playgroud)
data():{
return{
textRenderedAsItIs:`Hello
World`
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
40233 次 |
| 最近记录: |