11

Chrome appears to be doing something odd/interesting/confusing when I have a contenteditable section within a page. If you have a section of text that is wrapped with a <span> (maybe other tags, I dont know) that has a class applied to it that applies additional styling to the text (font family, color, etc) and then delete all the text in the editable section. When you start typing again, the text looks the same as you had when you started deleting text, but seems to be styled with the raw computed CSS, rather than having a span with the appropriate classes.

http://jsfiddle.net/tomprogramming/wS4Gp/

Any idea why this happens, or if I can turn it off? Firefox and IE both seem to keep the span with the class in it.

This is what I start with

<span class="level1" style="font-weight:bold;">This is level'd text</span>

and this is what I end up with

<span style="color: rgb(255, 255, 255); font-family: helvetica, arial, sans-serif; font-size: 48.18181610107422px; font-weight: bold;">This is level'd text</span>

And the relevant CSS

.editable .level1 {
    color: #fff;
    font-size:3em;
    font-family:helvetica, arial, sans-serif;
}

I understand what's going on, it's trying to behave like Word and other processors that retain your styling; however, these levels are important in our editor and should be retained. If they can't I'd rather just turn off this "feature".

4

1 回答 1

3

防止 Chrome 保留插入符号位置的旧计算样式的一种方法是清除浏览器选择,然后恢复它(以保留选择)。这应该在删除样式元素之后和插入新内容之前完成。执行以下操作:

let selection = window.getSelection();
if (selection && selection.rangeCount > 0 && selection.isCollapsed) {
  let range = selection.getRangeAt(0);
  selection.removeAllRanges();
  selection.addRange(range);
}
于 2019-02-26T13:37:20.603 回答