JQuery是廣泛使用的JavaScript庫(kù)之一。其中的onscrolltop()函數(shù),是在用戶上下滾動(dòng)網(wǎng)頁(yè)時(shí)被調(diào)用的函數(shù)。
$(window).scroll(function(){ if ($(this).scrollTop() >100) { // code to be executed when the page is scrolled down console.log("User has scrolled down"); } else { // code to be executed when the page is scrolled up console.log("User has scrolled up"); } });
以上代碼監(jiān)測(cè)了窗口滾動(dòng)事件,當(dāng)用戶向下滾動(dòng)窗口超過(guò)100px時(shí)觸發(fā)操作,例如在控制臺(tái)輸出 "User has scrolled down"。當(dāng)用戶返回到窗口的頂部時(shí),也會(huì)執(zhí)行相反的操作。
此外,onscrolltop()函數(shù)還可以用于實(shí)現(xiàn)“無(wú)限滾動(dòng)”功能,即當(dāng)用戶滾動(dòng)到頁(yè)面底部時(shí),自動(dòng)加載更多的數(shù)據(jù)。例如:
$(window).scroll(function(){ if($(document).height() - $(window).scrollTop() - $(window).height()< 50){ // code to be executed when user has scrolled to the bottom of the page console.log("User has reached the bottom of the page"); } });
以上代碼會(huì)在用戶滾到頁(yè)面底部時(shí)反應(yīng),輸出 "User has reached the bottom of the page"。此時(shí)開(kāi)發(fā)者可以編寫(xiě)相應(yīng)的代碼來(lái)加載更多的數(shù)據(jù),以實(shí)現(xiàn)“無(wú)限滾動(dòng)”功能。