0

Let's say I have a <div> element, which contains a very long text (real use case would be much longer):

aaaaa bbbbb ccccc ddddd eeeee fffff ggggg hhhhh iiiii jjjjj kkkkk lllll mmmmm nnnnn ooooo ppppp qqqqq rrrrr sssss ttttt uuuuu vvvvv wwwww xxxxx yyyyy zzzzz

The container <div> has rendered a vertical scroll bar. It rendered like this:

+---------------------+
| ddddd eeeee fffff |^|
| ggggg hhhhh iiiii | |
| jjjjj kkkkk lllll |||
| mmmmm nnnnn ooooo |||
| ppppp qqqqq rrrrr | |
| sssss ttttt uuuuu |v|
+---------------------+

I want a function which tells me where the <div> is scrolled. In this example, top most text is ddddd which has index 18 ('aaaaa bbbbb ccccc ddddd ...'.indexOf('ddddd') === 18). So the function should return 18.

HTMLElement only tells me the scrollTop in px, but not by how many characters. What should I do?

Notes:

  • If the top most texts are partial shown, they may be counted or may not. Any behavior is acceptable.
  • You may assume the <div> contains only plain texts. And you may assume no CSS rules like ::first-letter applied.
  • You may not assume mono-spaced fonts used as the ascii art shown above.
tsh
  • 4,263
  • 5
  • 28
  • 47
  • It's not clear what you are asking about. Do you want to know the vertical pixel position of the first text node that matches your query relative to the immediate parent? Or to the body? Can you please clarify? – jsejcksn Feb 29 '20 at 20:38
  • @jsejcksn i had done a mirror edit to make it clear as i can. hope it work. – tsh Feb 29 '20 at 22:39
  • If you can post an actual code sample, it might be possible to provide an answer. See https://stackoverflow.com/help/minimal-reproducible-example – jsejcksn Feb 29 '20 at 22:41
  • @jsejcksn im not asking for debugging a not working snippet. but ask for the way (maybe an api, maybe some algorithm) to get the result. i dont think a reproducible example may help. – tsh Feb 29 '20 at 22:44
  • I just searched out this question: https://stackoverflow.com/a/29903556/2045384 . The answer may get position about certain characters. And it could be done by a binary search. It could be a possible way at least. – tsh Mar 03 '20 at 11:49

0 Answers0