js 判斷滾動條 是否滾動到底部
解決問題思路
滾動條距離上面的滾動高度(scrollTop) + 滾動條本身高度 = 整個頁面的高度(pageHeight)
關鍵點:滾動條本身高度是多少
事實上,這里就有一個思想誤區,人會想直接獲取滾動條高度(但找不到這個API,同時滾動條表現出來的高度,也會雖內容變長變短)。
其實你只要考慮一下,為什么會出現滾動條。出現滾動條代表超出可視窗口,它的滾動距離就是超出部分,而可視窗口高度就是滾動條對應的真實高度。
//滾動條距離頂部高度 function getScrollTop() { var scrollTop=0; if(document.documentElement&&document.documentElement.scrollTop) { scrollTop=document.documentElement.scrollTop; } else if(document.body) { scrollTop= document.body.scrollTop; } return Math.ceil(scrollTop); } //滾動條本身高度:就是可視窗口高度 function getScrollBarHeight(){ let scrollBarHeight = document.documentElement.clientHeight; return Math.ceil(scrollBarHeight); } //整個頁面高度 function getPageHeight() { return Math.ceil(Math.max(document.body.clientHeight,document.documentElement.scrollHeight)); } window.onscroll = function () { let top = getScrollTop(); let ch = getScrollBarHeight(); let sh = getPageHeight(); if (top + ch >= sh) { console.log("到達底部"); }else{ console.log("沒有到達底部"); } }

浙公網安備 33010602011771號