HTML - DIV 内容中的换行符可编辑吗?

问题描述 投票:0回答:5

我正在将内容存储在数据库中,例如:

Hello
This
is 
Text

当我将其传递到文本区域时,它会保留新的换行符。但如果我将该文本传递给内容可编辑的 div,它将保持如下所示:

Hello This is Text

如何解决这个问题?

css html contenteditable
5个回答
152
投票

在 div 上设置样式:

white-space: pre
white-space: pre-wrap

示例:http://jsfiddle.net/fPv6S/


20
投票

添加一些有关 @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>

编辑2018年8月14日:

在 Chrome 中,您可能会遇到麻烦:按 Enter 将在您的可编辑内容中生成一个新的

<div>
。为了防止这种情况,您可以按 Shift+Enter 或将
display: inline
设置为内容可编辑
<div>
,如小提琴所示。


6
投票

试试这个......

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,"");

这样就可以了...


1
投票

您可以使用

<br />
搜索并替换换行符。 http://jsfiddle.net/fPv6S/1/


0
投票

对我来说,这些解决方案都不起作用。 例如,在检查了可编辑 div 中的

<p>
元素后,我发现默认浏览器样式添加了
top
bottom
边距,因此我将其添加到了 CSS 中:

ul, ol {
    line-height: 7px;
}

p {
    margin:7px 0px;
}
© www.soinside.com 2019 - 2024. All rights reserved.