I have an HTML textarea as a basis for a small text editor running inside Chrome, which includes search functionality (as I need search features beyond what the browser offers). For longer texts, this means I need the JavaScript to scroll to the correct position after selecting the found text. This works fine by calculating the font's line height times the found text's row number (the latter I get by counting line breaks) and then setting textareaElement.scrollTop... but only when the textarea is set to wrap="off". When it wraps, as I sometimes need it, I cannot simply count the rows by counting line breaks, and my scroll position开发者_Python百科 algo will be off by a bit.
What can I do to get the correct position of the found, selected text?
I've tackled this issue for the search feature of the logging console in log4javascript. My code surrounds search results in tags whose style properties are changed as you flick through search results. Initially I called scrollIntoView()
on the current search result span but I think I had problems in certain browsers (log4javascript supports IE 5, for example) and ended up writing my own scrolling function based on the offsetLeft
and offsetTop
properties of the span and the scrollLeft
and scrollTop
properties of the container. I suspect scrollIntoView()
will work fine in Chrome though so you should be OK just using that.
精彩评论