简体   繁体   中英

Caret position is way off in contenteditable div

Chrome (and maybe other browsers) position the caret in a strange way within a contenteditable div.

Please consider the following snippet:

<div contenteditable="true" style="width: 100%; height: 200px; border: 1px solid black; overflow: auto;">
    <p>
        <span contenteditable="false" style="width: 75%; height: 80px; display: inline-block; border: 1px solid red;">&nbsp;</span>.
    </p>
</div>

Also available in this JSFiddle .

If you click on the right-side of the period next to the red span and press backspace to delete the period, the caret suddenly shifts to the extreme right of the paragraph. I would expect the caret to be positioned where the period used to be, next to the red span.

Why is it not positioned the way I expect, and is there a way to get the behavior I'm looking for?

This strange behavior is happening because of the p tag, the cause is possibly some conflict between widths, you can edit the css of the tag, instead of using display:block (default), use display:inline .

I created this fiddle: JsFiddle , with display:inline , was the closest I could get from the display:block .

I tried the align attribute but I did not succeed.

I'm fairly confident that it's the span causing it, because the moment you remove it or even display: none it, the problem goes away. I got really curious about this myself and did some searching, this person seems to have the same problem as you.

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

Non-breaking spaces are just what they sound like — spaces where a line break will not occur. You should not use them to add space between words, sentences, or elements. Especially not elements.

Remove & nbsp; (with space or will actually make space :D) and everything's good.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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