find top and last element inside a scrollable div

不打扰是莪最后的温柔 提交于 2019-12-08 07:33:17

问题


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.


回答1:


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




回答2:


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.




回答3:


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!)




回答4:


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()


来源:https://stackoverflow.com/questions/1757106/find-top-and-last-element-inside-a-scrollable-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!