Why Is My Contenteditable caret Jumping to the End in Chrome?

后端 未结 6 1608
攒了一身酷
攒了一身酷 2020-12-10 01:59

Scenario

I have a contenteditable

area, and within this area I may have some
6条回答
  •  死守一世寂寞
    2020-12-10 02:12

    The problem is that your contenteditable element is a div, which by default is display: block. This is what causes your caret position problem. This can be fixed by making the outermost div non-editable and adding a new editable div that will be treated as inline-block.

    The new HTML would have a new div just inside the outer one (and the corresponding closing tag at the end):

    ...

    And add this to your CSS:

    div#editable {
        display: inline-block;
    }
    

    For the sake of seeing the caret better when it is between span elements, I've also added margin: 2px to the rule for div.main span in the CSS but this is not necessary to prevent the caret jumping issue reported in the question.

    Here is a fiddle.

    As you've started discovering, contenteditable is handled inconsistently across browsers. A few years back, I started working on a project (in-browser XML editor) where I thought contenteditable would make everything easier. Then as I developed the application, I soon found myself taking over the functions that I thought contenteditable would give me for free. Today, the only thing contenteditable give me is that it turns on keyboard events on elements I want to edit. Everything else, including caret movement and caret display, is managed by custom code.

提交回复
热议问题