简体   繁体   English

div contenteditable和带有span元素的自动换行

[英]div contenteditable and word-wrapping with span elements

When I have span tags in a contenteditable div the word wrapping changes. 当我在contenteditable div中有span标签时,自动换行就会改变。 Here is a fiddle. 这是一个小提琴。 http://jsfiddle.net/knpB9/ http://jsfiddle.net/knpB9/

<div contenteditable="true" style="width:168px; border:1px solid black;">aaaaaaaa-bbbbbbbb-ccccccc</div>
<br>
<div contenteditable="true" style="width:168px; border:1px solid black;">aaaaaaaa-bbbbbbbb-<span style="color:red;">ccccccc</span></div>

How do I keep the word wrapping the same regardless of the html tags? 无论html标签如何,换行都一样。

If you want to preserve the normal line breaks you can set the span to display: inline-block; 如果要保留正常的换行符,可以将跨度设置为display: inline-block; .

Here's a jsFiddle . 这是一个jsFiddle

This bit of CSS does the trick if you don't care about lines breaking in the middle of a word: 如果您不关心单词中间的断行,那么这段CSS可以解决问题:

div
{
    white-space: pre;
}

Here's a jsFiddle . 这是一个jsFiddle

Have a look here to read up on how and why it works the way it does. 看看这里以了解其工作方式以及工作方式的原因。

Update 更新资料

The reason why it wraps the way it does in you last jsFiddle is because the hyphens provide the browser with a soft wrap opportunity . 之所以用最后一个jsFiddle来包装它,是因为连字符为浏览器提供了换行的机会 You could replace those with a non-breaking hyphen or &#8209; 你可以取代那些非破连字符&#8209; and it should wrap the as expected again. 并且应该再次按预期包装。 You could write some JS that would capture every keypress on the contenteditable element, then cancels its normal behaviour if the hyphen key is pressed, and inserts the non-breaking hyphen instead of the normal hyphen 您可以编写一些JS来捕获contenteditable元素上的每个按键,然后在按下连字符键的情况下取消其正常行为,并插入不间断的连字符而不是普通的连字符。

Here's a jsFiddle . 这是一个jsFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM