Cursor in wrong place in contenteditable

2019-07-02 05:12发布

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?

2条回答
We Are One
2楼-- · 2019-07-02 05:41

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.

查看更多
爷的心禁止访问
3楼-- · 2019-07-02 05:42
&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

查看更多
登录 后发表回答