|
|
|
|
|
前面已經(jīng)介紹過JS兩種方法滾動條上滾下滾顯示隱藏導航欄【親測可用】,以及【親測!3種方法】JS判斷滾動條上滾下滾,本文將通過3個實例演示,介紹JS判斷滾動條/某div是否到達底部/頂部。
當滾動條到達底部時,導航欄消失。
window.addEventListener("scroll", function(event)
{
event = event || window.event;
var scrollTop = $(this).scrollTop();
console.log("$(this).scrollTop()=" + $(this).scrollTop());
var documentHeight = $(document).height();
console.log("$(document).height()=" + $(document).height());
var windowHeight = $(window).height();
console.log("$(window).height()=" + $(window).height());
if (scrollTop + windowHeight == documentHeight)
{
document.getElementById("tip").style.display = "none";
}
else
{
document.getElementById("tip").style.display = "block";
}
});
代碼主要用到三個函數(shù)值:滾動條高度$(this).scrollTop()
,窗口高度$(window).height()
、文檔高度$(document).height()
。
判斷方法是:當 滾動條高度+窗口高度=文檔高度 時,滾動條到達底部。
這三個高度的含義及關(guān)系,你可以看此文一圖理解$(this).scrollTop()、$(window).height()與$(document).height()關(guān)系。
如果你理解了實例一的代碼那三個高度的含義及它們的關(guān)系,那么判斷滾動條是否到達頂部就輕而易舉了。
當滾動條到達頂部時,導航欄消失。
window.addEventListener("scroll", function(event)
{
event = event || window.event;
var scrollTop = $(this).scrollTop();
if (scrollTop == 0)
{
document.getElementById("tip").style.display = "none";
}
else
{
document.getElementById("tip").style.display = "block";
}
});
代碼非常簡短,只需使用一個函數(shù)$(this).scrollTop()
,這個函數(shù)是獲得滾動條的位置。
判斷條件:滾動條的位置高度為0,即代表滾動條在頂部位置。
在實際應用中,我們經(jīng)??吹侥砫iv隨網(wǎng)頁從下往上滾到窗口底部時就顯示出來。這個也好辦,我們只需獲得此div的位置,然后利用它,結(jié)合滾動條高度和文檔高度,即可判斷出該div是否到達了底部。
當【網(wǎng)站速度診斷】到達網(wǎng)頁底部時,導航欄消失。
window.addEventListener("scroll", function(event)
{
event = event || window.event;
var scrollTop = $(this).scrollTop(); //滾動條高度
var documentHeight = $(document).height(); //文檔高度
var windowHeight = $(window).height(); //窗口高度
var divTop = document.getElementById("divTarget").offsetTop; //目標div高度
if (scrollTop + windowHeight > divTop)
{
document.getElementById("tip").style.display = "none";
}
else
{
document.getElementById("tip").style.display = "block";
}
});
重點是要獲得目標div
的高度,在JS里很容易就能實現(xiàn),只需這個方法就能獲得:
document.getElementById("divTarget").offsetTop
得到目標div的高度之后,再按照實例一的方法,判斷條件是:滾動條高度 + 窗口高度 > 目標div高度。
本文介紹了三個常見的實例,主要是運用了滾動條高度$(this).scrollTop()
,窗口高度$(window).height()
、文檔高度$(document).height()
的知識,實現(xiàn)我們想要的功能效果。
參考文章