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("沒有到達底部");
            }
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM