Cursor in wrong place in contenteditable

2019-07-02 05:42发布

问题:

I have contenteditable div with non-editable "islands". Everything is working well until non-editable part is the last thing in editable div. In that case cursor is not right behind non-editable but at the very end of editable div.

See this example I borrowed from this question

Here is fiddle you can try on: http://jsfiddle.net/RYsvZ/2/ . When you delete dot at the end, cursor jump away. This behaviour is with safari and chrome. I guess it is webkit issue.

Here is code sample:

<div contenteditable="true" class="editor">
Sample template with <span class="mergecode" contenteditable="false">MergeCode1</span>.
</div>

Do you have any idea why it is happening and how to fix it?

回答1:

&zwnj;<button contenteditable=false>press</button>&zwnj;

The problem is caused by the caret having no space to go into so if you wrap your contenteditable divs in zero width non joining spaces it gives the caret somewhere to go.

jsfiddle



回答2:

This happens when contenteditable=false is last child of

element. As I know, this is webkit bug. You always make sure the "contenteditable=false" is wrapped a hidden_char or zero-width-white-space:

  • HIDDEN_CHAR: "\ufeff"
  • ZERO_WIDTH_WHITESPACE: "​"

If you use tinymce, you can use onNodeChange event or check when delete/backspace happens and validate all "contenteditable=false" nearby the cursor.