jquery 如何检查滚动条是否在底部

smdnsysy  于 2023-03-22  发布在  jQuery
关注(0)|答案(5)|浏览(156)

如何检查滚动条是否位于底部?使用JQuery或JavaScript

1l5u6lss

1l5u6lss1#

找到滚动容器的高度,然后将其与滚动位置进行比较。如果它们相同,则已到达底部。

<div style="overflow: auto; height: 500px">
</div>

$(document).ready(function()
{
   $('div').scroll(function()
   {
      var div = $(this);
      if (div.height() == div.scrollTop() + 1) //scrollTop is 0 based
      {
          alert('Reached the bottom!");
      }
   });
});

编辑:在js小提琴上做了一点测试,我意识到以前的版本是不正确的。你可以使用DOM属性来找出有多少滚动,然后像这样对元素的高度进行一点数学计算。

var div = $(this);
      if (div[0].scrollHeight - div.scrollTop() == div.height())
      {
          alert('Reached the bottom!');
      }

http://jsfiddle.net/Aet2x/1/

ryoqjall

ryoqjall2#

这在我的聊天窗口中运行良好。它还能检测内容是否不够长而无法滚动。

function atBottom(ele) {
    var sh = ele.scrollHeight;
    var st = ele.scrollTop;
    var ht = ele.offsetHeight;
    if(ht==0) {
        return true;
    }
    if(st == sh - ht)
        {return true;} 
    else 
        {return false;}
}

更新:有人建议这个编辑是为了同一代码的更干净的版本。我喜欢我更详细的版本作为答案,但它是一个好主意,有两个可用。

function atBottom(el) {
    let sh = el.scrollHeight,
    st = el.scrollTop,
    ht = el.offsetHeight;
    if (ht == 0) return true;
    return st == sh - ht; 
}
hxzsmxv2

hxzsmxv23#

这对我来说很有用(使用jQuery):

$(document).ready(function(){
  $('div').scroll(function(){
    //scrollTop refers to the top of the scroll position, which will be scrollHeight - offsetHeight
    if(this.scrollTop == (this.scrollHeight - this.offsetHeight)) {
      console.log("Top of the bottom reached!");
    }
  });
});

取自here

bt1cpqcv

bt1cpqcv4#

可以检查元素scrollTop是否等于元素innerHeight

if($('div').scrollTop() == $('div').innerHeight()){
    //Reached the bottom
}
bvn4nwqk

bvn4nwqk5#

let div = document.getElementById("div");
if ((div.scrollHeight - div.scrollTop) == div.clientHeight) {
  alert('at Bottom');
}
<div id="div" style="overflow:auto; height=700px">
 
</div>

相关问题