一、直接獲取滾動條高度
window.pageYOffset document.documentElement.scrollTop || document.body.scrollTop
可以直接通過window.pageYOffset或document.documentElement.scrollTop || document.body.scrollTop獲取頁面滾動條在Y軸上的滾動距離(單位為像素),這兩個屬性均可兼容大多數主流瀏覽器。
代碼示例:
var scrollHeight = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; console.log('滾動高度:' + scrollHeight);
二、jQuery獲取滾動條高度
$(window).scrollTop()
使用jQuery框架也可以輕鬆獲取滾動條高度,只需要調用$(window).scrollTop()即可返回滾動條在Y軸上的滾動距離(單位為像素)。
代碼示例:
var scrollHeight = $(window).scrollTop(); console.log('滾動高度:' + scrollHeight);
三、滾動事件獲取滾動條高度
document.addEventListener('scroll', function(){ console.log('滾動高度:' + window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop); })
通過監聽滾動事件,實時獲取滾動條的高度,可以提高用戶體驗。
代碼示例:
document.addEventListener('scroll', function(){ var scrollHeight = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; console.log('滾動高度:' + scrollHeight); });
四、節流優化滾動條高度獲取
function throttle (fn, delay) { let last; return function () { const context = this; const args = arguments; const now = +new Date(); if (!last || now > last + delay) { fn.apply(context, args); last = now; } } } document.addEventListener('scroll', throttle(function(){ var scrollHeight = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; console.log('滾動高度:' + scrollHeight); }, 300));
如果在滾動事件中直接寫獲取滾動條高度的代碼,會造成事件的頻繁觸發,造成頁面卡頓。為了優化性能,可以對滾動事件進行節流,控制事件的觸發間隔,提高用戶體驗。
代碼示例:
function throttle (fn, delay) { let last; return function () { const context = this; const args = arguments; const now = +new Date(); if (!last || now > last + delay) { fn.apply(context, args); last = now; } } } document.addEventListener('scroll', throttle(function(){ var scrollHeight = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; console.log('滾動高度:' + scrollHeight); }, 300));
五、滾動到底部加載更多
document.addEventListener('scroll', throttle(function(){ var scrollHeight = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; var pageHeight = document.documentElement.scrollHeight || document.body.scrollHeight; if (scrollHeight + window.innerHeight >= pageHeight) { console.log('已滾動到頁面底部,執行加載更多操作'); } }, 300));
在一些需要加載更多數據的場景中,可以通過監聽滾動事件判斷滾動條是否到達頁面底部,從而自動觸發加載更多的操作。
代碼示例:
document.addEventListener('scroll', throttle(function(){ var scrollHeight = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; var pageHeight = document.documentElement.scrollHeight || document.body.scrollHeight; if (scrollHeight + window.innerHeight >= pageHeight) { console.log('已滾動到頁面底部,執行加載更多操作'); } }, 300));
六、總結
本文介紹了JavaScript中獲取滾動條高度的多種方法,包括直接獲取滾動條高度、jQuery獲取滾動條高度、滾動事件獲取滾動條高度、節流優化滾動條高度獲取和滾動到底部加載更多等方面。無論是在滾動監測、懶加載、無限加載還是製作瀑布流等方面都是必不可少的技術。開發者可根據項目需求選擇合適的方法,提高網頁加載速度和用戶體驗。
原創文章,作者:JJMMD,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/372982.html