Maintaining aesthetic scroll in contenteditable di

2019-04-28 01:49发布

问题:

I'm building a Rich Text Editor using a contenteditable div, and I find that when I have written more content than fits the screen and I scroll so that the cursor is no longer at the bottom, and I start typing again, the scroll defaults to putting the cursor at the bottom of the screen again.

When I try the jquery e.preventDefault from the keydown or keypress, of course it stops, but then I can't type anything either! If I continue down that route, unless I can find a way of targeting only this particular behavior, I'll end up having to script the entire of the contenteditable behaviour!

How do I keep the scroll where the user want's it?

How do aloha and CKeditor manage it??

EDIT: This happens even if the editor-window div is set to overflow: hidden!

<div id="editor-window" class="hbox flex">
    <div id="editor" >
        <div id="editor-content" contenteditable>
            <p class="slug"></p>
        </div>
    </div>
</div>

EDIT: Actually I'm finding that it doesn't just scroll to put the cursor at the bottom, its scrolling seems quite erratic. The cursor doesn't leave the screen, which I'm guessing is the purpose for this behaviour, but still its erratic none the less.

回答1:

If you would look deep enough or just "inspect element" near the editor you would find out that it is based on an iframe.

I wouldn't recommend you to keep on developing using div as a stage. Furthermore, the iframe would solve your scrolling problem. Here is a link that shows how to insert html to iframe created with javascript here

Good Luck!