我正在将内容存储在数据库中,例如:
Hello
This
is
Text
当我将其传递到文本区域时,它会保留新的换行符。但如果我将该文本传递给内容可编辑的 div,它将保持如下所示:
Hello This is Text
如何解决这个问题?
添加一些有关 @Explosion Pills 正确答案的信息并从 MDN 中提取一些信息:
CSS
white-space
属性可以提供帮助:
white-space: pre
保留空白序列。仅在以下位置断线 源中和
元素中的换行符。<br>
这可能会导致出现不需要的水平滚动条,如示例所示!
white-space: pre-wrap
保留空白序列。换行符处断行 字符,位于
,并根据需要填充行框。<br>
正如 @ceremcem 指出的那样,复制粘贴文本时,框末尾的换行符不会被转移,这是有道理的,因为这些换行符不是文本格式的一部分,而是视觉外观的一部分。
white-space: pre-line
空白序列被折叠。换行符处断行 字符,位于
,并根据需要填充行框。<br>
div{
border: 1px solid #000;
width:200px;
}
.pre {
white-space: pre;
}
.pre-wrap{
white-space: pre-wrap;
}
.pre-line{
white-space: pre-line;
}
.inline-block{
display:inline-block
}
<h2>
pre
</h2>
<div class="pre" contenteditable=true>Lorem ipsum dolor sit amet doesn't have a meaning but here comes 10 white spaces:____ ____</div>
<h2>
pre-wrap
</h2>
<div class="pre-wrap" contenteditable=true>Lorem ipsum dolor sit amet doesn't have a meaning but here comes 10 white spaces:____ ____</div>
<h2>
pre-line
</h2>
<div class="pre-line" contenteditable=true>Lorem ipsum dolor sit amet doesn't have a meaning but here comes 10 white spaces:____ ____</div>
<h2>
Chrome FIX
</h2>
<div class="pre-line inline-block" contenteditable=true>Lorem ipsum dolor sit amet doesn't have a meaning but here comes 10 white spaces:____ ____</div>
在 Chrome 中,您可能会遇到麻烦:按 Enter 将在您的可编辑内容中生成一个新的
<div>
。为了防止这种情况,您可以按 Shift+Enter 或将 display: inline
设置为内容可编辑 <div>
,如小提琴所示。
试试这个......
var patt2 = new RegExp("<div>","g");
var patt3= new RegExp("</div>","g");
var patt4= new RegExp("<br>","g");
var z=x.replace(patt2,"\n").replace(patt3,"").replace(patt4,"");
这样就可以了...
对我来说,这些解决方案都不起作用。 例如,在检查了可编辑 div 中的
<p>
元素后,我发现默认浏览器样式添加了 top
和 bottom
边距,因此我将其添加到了 CSS 中:
ul, ol {
line-height: 7px;
}
p {
margin:7px 0px;
}