欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

jQuery檢測滾動條是否到達(dá)底部

 更新時間:2015年12月15日 11:34:00   投稿:lijiao  
這篇文章主要介紹了jQuery檢測滾動條是否到達(dá)底部的實現(xiàn)方法,文中介紹了兩種檢測滾動條到達(dá)底部的狀況,感興趣的小伙伴們可以參考一下

一、jQuery檢測瀏覽器window滾動條到達(dá)底部
jQuery獲取位置和尺寸相關(guān)函數(shù):
$(document).height()    獲取整個頁面的高度
$(window).height()    獲取當(dāng)前也就是瀏覽器所能看到的頁面的那部分的高度。這個大小在你縮放瀏覽器窗口大小時會改變,與document是不一樣的
scrollTop()    獲取匹配元素相對滾動條頂部的偏移。
scrollLeft()    獲取匹配元素相對滾動條左側(cè)的偏移。
scroll([[data],fn])    當(dāng)滾動條發(fā)生變化時觸犯scroll事件
jQuery檢測滾動條到達(dá)底部代碼:

$(document).ready(function() {
  $(window).scroll(function() {
 
    if ($(document).scrollTop()<=0){
      alert("滾動條已經(jīng)到達(dá)頂部為0");
    }
 
    if ($(document).scrollTop() >= $(document).height() - $(window).height()) {
      alert("滾動條已經(jīng)到達(dá)底部為" + $(document).scrollTop());
    }
  });
});

二、jQuery檢測div中滾動條到達(dá)底部
上半篇介紹了jQuery檢測瀏覽器window滾動條到達(dá)底部,其實還并不理解scrollTop和scrollHeight概念,通常滾動條都是放在div中的。


如下檢測id為scroll_div滾動條到達(dá)底部事件:

<div id="scroll_div" style="overflow-y:auto; overflow-x:hidden;margin:100px;height:500px;border:1px solid red">
      <div style="height:10000px">
        來自于www.dbjr.com.cn腳本之家<br>
        來自于www.dbjr.com.cn腳本之家<br>
        來自于www.dbjr.com.cn腳本之家<br>
      </div>
    </div>

首先需要理解幾個概念:
scrollHeight:表示滾動條需要滾動的高度,即內(nèi)部div,10000px
scrollTop: 表示滾動條滾動的高度,可能大于外部div 500px
也就是說scrollDiv的高度+scrollTop滾動的最大高度=scrollHeight
于是檢測div中div滾動條高度就簡單了:

$(document).ready(function() {
  $("#scroll_div").scroll(function(){
    var divHeight = $(this).height();
    var nScrollHeight = $(this)[0].scrollHeight;
    var nScrollTop = $(this)[0].scrollTop;
    $("#input1").val(nScrollHeight);
    $("#input2").val(nScrollTop);
    $("#input3").val(divHeight);
    if(nScrollTop + divHeight >= nScrollHeight) {
      alert("到達(dá)底部了");
    }
  });
});

如果是異步加載數(shù)據(jù),數(shù)據(jù)沒加載完,又觸犯了同一頁的數(shù)據(jù)加載請求,我通常是加一個flag

$(document).ready(function() {
  var flag = false;
  $("#scroll_div").scroll(function(){
    
    if(flag){
      //數(shù)據(jù)加載中
      return false;
    }
    
    var divHeight = $(this).height();
    var nScrollHeight = $(this)[0].scrollHeight;
    var nScrollTop = $(this)[0].scrollTop;
    $("#input1").val(nScrollHeight);
    $("#input2").val(nScrollTop);
    $("#input3").val(divHeight);
    if(nScrollTop + divHeight >= nScrollHeight) {
      //請求數(shù)據(jù)
      flag = true;
      alert("到達(dá)底部了");
    }
  });
});

相關(guān)文章

最新評論