简体   繁体   中英

Scroll to a text position in Javascript

I have a real-time HTML editor, with a textarea on the left for code entry, and a 'preview' DIV on the right to contain the preview of the code entered. At the moment, when editing the code in the left pane, the preview just sits where it is, so often the part of the code you're editing is not in the visible area of the preview (especially when images are involved).

My question is how do I make the preview scroll to show the part of the code that's currently being edited?

Here is the page I have so far: http://www.caerphoto.com/rtedit.html You'll notice in the source I have a (currently unused) matchPreview() function that tries to match the scroll position of the preview based on the scroll position of the textarea, but obviously if images or large text are involved the two panes no longer match.

尝试使用标签代替克隆目标的div。

let me decompose your task into 2 subtasks:

  1. get informed when the dom changes you could listen on changes of the dom like onsubtreemodified.

see en.wikipedia.org/wiki/DOM_events

  1. scroll the element into view

the answer to this is the scrollintoview method:

see www.quirksmode.org/dom/tests/scrollintoview.html

however, this might not help you too much, since you are updating the whole html document on every change of the textarea. since you cannot get the position of the cursor inside the textarea, this might be not that easy.

sorry mate, at the end I have no solution, but maybe my rumination helps in some way nevertheless.

good luck!

When I tried this in Firefox. no line-breaks were seen in the preview; is this correct? I may be able to help ( done something similsr recently ), but not if the line breaks are removed...

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