简体   繁体   中英

find top and last element inside a scrollable div

I have a scrollable div with a fixed height. While scrolling I need to get the element at the top of the visible viewport and the one at the bottom of the viewport. I can get the position of the scrollbar using scrollTop, however I am not sure how to get the element.

Update: Formatted question for clarity.

Get your div's scroll position

var scrollY = document.getElementById("yourDiv").scrollTop;

Loop through the elements inside and look at their position

var divs = document.getElementById("yourDiv").getElementsByTagName("div");
alert(divs[0].offsetTop)

Figure out which one is at the scrollTop position and the other one is at scrollTop + height position

You should loop through the div using DOM elements. Take a look here, I think it might be a usefull resource: http://www.howtocreate.co.uk/tutorials/javascript/dombasics

With some arrays and counters you should be able to get the last element in your div.

I assume that your DIV is a long list of text lines, and all your lines will be of uniform height. If this is true, then you don't need to ask which one is at the top of the viewport, as you will be able to calculate it.

You'll want to be displaying the first page of this stuff in full anyway, so you create one complete and displayable line, ask it for its height and remember that. Then you add some more text-containing lines until the total height of them is greater than the height of the window. Then, add 1990 or so empty lines so that the thumb's size and position accurately reflect the size of the list.

Then, when someone scrolls your window, you can calculate which lines should be visible; zap those that have moved out of view and build up the ones that should be visible. Done!

(I think - I've never tried this!)

Or you could try using firstElementChild and lastElementChild :

first = document.querySelector('#your_div_id_or_selector').firstElementChild; 
first.scrollIntoView()

and for last element

last = document.querySelector('#your_div_id_or_selector').lastElementChild;
last.scrollIntoView()

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