I have a div
with many textual lines开发者_JS百科 in it. The div is height restricted and hence I have a scroll
. Is there a way in java script
to scroll to a specified line.
Had it been in html
page I can always do it with bookmarks , how to do it for rich text boxes or any html container
with the help of java script.
Any help much appreciated.
Nandish
The problem you have here is the concept "line". Since you have a box drawn in the browser, with a given width (maybe dynamic), and a text inside it, the lines depends on the wrapping.
For example, the text: "hello world, I need my pizza now" would be two lines if the width is really small, or a single line, if the width is enough to fit this text.
What I mean with this, is that "line" is a concept relative to the wrapping itself, so even counting lines inside a div its not possible.
It is different if your lines are defined by the user, with line feeds and carriage returns, or with
or whatever, but if the lines are generated by the wrapping, this happens at rendering time, and you have no idea of how it would happen.
If you have a fixed font size, you can speculate the number of lines, by a simple division of the height of the box / font size + space between lines.
However, if you text is rich, it can contain images, etc, and this won't work.
Another possible solution is to use getClientRects (this worked for me)
https://developer.mozilla.org/en/DOM/element.getClientRects
that returns a collection of text rectangles objects:
http://help.dottoro.com/ljgupwlp.php
Hope this helps a bit, I faced this problem twice before, and its not as easy a function call, you should understand what means lines, wrapping, clienrects, textrectangles, fonts...
Good luck!
If you mean a <div contenteditable="true">
, you can try this: http://jsfiddle.net/cMMy5/.
Basically it is the scrollTop
property of the div.
$div = $('div');
$('button').click(function() {
$div.get(0).scrollTop = 10;
});
精彩评论