本文實(shí)例講述了jQuery實(shí)現(xiàn)判斷滾動(dòng)條滾動(dòng)到document底部的方法。分享給大家供大家參考,具體如下:
滾動(dòng)條沒(méi)有實(shí)際的高度。只是為了呈現(xiàn)效果才在外型上面有長(zhǎng)度。
在js當(dāng)中也沒(méi)有提供滾動(dòng)條的高度API。
參考了網(wǎng)上有關(guān)資料:判斷滾動(dòng)條到底部的基本邏輯是滾動(dòng)條滾動(dòng)的高度加上視口的高度,正好是document的高度,公式表示為
滾動(dòng)條滾動(dòng)的高度+瀏覽器視口的高度>=document的高度。
參考網(wǎng)上資料,具體代碼如下:
//滾動(dòng)條在Y軸上的滾動(dòng)距離function getScrollTop() { var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0; //兼容谷歌 if (document.body) { bodyScrollTop = document.body.scrollTop; } //兼容火狐 if (document.documentElement) { documentScrollTop = document.documentElement.scrollTop; } scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop; return scrollTop;}//文檔的總高度f(wàn)unction getScrollHeight() { var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0; //兼容谷歌 if (document.body) { bodyScrollHeight = document.body.scrollHeight; } //兼容火狐 if (document.documentElement) { documentScrollHeight = document.documentElement.scrollHeight; } scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight; return scrollHeight;}//瀏覽器視口的高度f(wàn)unction getWindowHeight() { var windowHeight = 0; windowHeight = document.documentElement.clientHeight; return windowHeight;}window.onscroll = function() { if (getScrollTop() + getWindowHeight() == getScrollHeight()) { alert("you are in the bottom!"); }};
jquery實(shí)現(xiàn)代碼:
$(window).scroll(function(){ var scrollTop = $(this).scrollTop(); var scrollHeight = $(document).height(); var windowHeight = $(this).height(); if(scrollTop + windowHeight == scrollHeight){ alert("you are in the bottom"); }});
代碼測(cè)試有效果。
感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運(yùn)行工具:http://tools.VeVB.COm/code/HtmlJsRun測(cè)試上述代碼運(yùn)行效果。
更多關(guān)于jQuery相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《jQuery頁(yè)面元素操作技巧匯總》、《jQuery常見(jiàn)事件用法與技巧總結(jié)》、《jQuery常用插件及用法總結(jié)》、《jQuery擴(kuò)展技巧總結(jié)》及《jquery選擇器用法總結(jié)》
希望本文所述對(duì)大家jQuery程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注