jQuery : how to determine that a div is scrolled d

2019-02-05 07:23发布

I have a div with defined height, and overflow:scroll;. Its content is too long so scrollbars appear.

Now for the ichy part. Some of its inner HTML strangely appears all the time (to be precise, the footer of a table generated by the tableFilter plugin). I'd like to make this footer disappear when it is not needed (it actually appears out of the containing <div>'s border). I resolved to make it disappear but setting its z-index to -1000. But I want to make it appear when the containing <div> is totally scrolled down.

How can I know the user has scrolled at the bottom ?


Using the help from answers below, I used scrollTop attribute but the difference between scrollTop and innerHeight is the size of the scrollbar plus some unidentified delta. A scrollbar is 16 pixels high in most browsers under Windows, but I get a difference of 17 in Firefox and something like 20 in IE, where my <div> content's borders seems to be rendered bigger.

A way (actually two ways...) to compute the scrollbar size has been given there.

标签: jquery scroll
7条回答
beautiful°
2楼-- · 2019-02-05 07:37

You need to compare the div height with the scrollTop position and the element height.

$(div).scroll(function(){ 
  if(isScrollBottom()){ 
    //scroll is at the bottom 
    //do something... 
  } 
}); 

function isScrollBottom() { 
  var elementHeight = $(element).height(); 
  var scrollPosition = $(div).height() + $(div).scrollTop(); 
  return (elementHeight == scrollPosition); 
} 
查看更多
我命由我不由天
3楼-- · 2019-02-05 07:38

This is not limited to divs:

toallyScrolled = element.scrollHeight - element.scrollTop === element.clientHeight;

from MDN Element.scrollHeight. There's also a nice demo on that page.

查看更多
地球回转人心会变
4楼-- · 2019-02-05 07:51
function elementInViewport(el) {
   var listcontent= $(".listContainer")[0].getBoundingClientRect();
   var rect = $(el)[0].getBoundingClientRect();
   return [( rect.top >= 0 && rect.left >= 0 && rect.bottom <=  listcontent.bottom), ( rect.bottom - listcontent.bottom )]
}
查看更多
Summer. ? 凉城
5楼-- · 2019-02-05 07:59

You can know if the div is scrolled down by simply doing this:

 if ( div.scrollTop + div.clientHeight == div.scrollHeight ){
 //...
 }

It works on Firefox, Chrome and IE8

查看更多
再贱就再见
6楼-- · 2019-02-05 08:04

No jQuery needed to get that info:

element.scrollTop;

In a scroll event of your DIV, use that info to check against the height of the element, if it matches (or is close to matching) do whatever you want.

查看更多
我命由我不由天
7楼-- · 2019-02-05 08:04

You just need to use the scrollHeight property of the div instead of height. The function isScrollBottom() which Shaun Humphries wrote previously can be put like this

function isScrollBottom() {
var totalHeight = $("divSelector")[0].scrollHeight;
var scrollPosition = $("divSelector").height() + $("divSelector").scrollTop();
return (totalHeight == scrollPosition);
}
查看更多
登录 后发表回答