jQuery判斷頁面滾動條距離頂端位置


今天利用空閑時間,研究了一下瀏覽器滾動條的簡單控制,主要是通過jQuery獲取滾動條的位置信息,直接上代碼

1、當前窗口高度

$(window).height();

2、滾動條已滾動高度

$(window).scrollTop();

3、結合jQuery來實時獲取滾動條滾動距離信息

 1 $(window).on('scroll',()=>{
 2         let $fixedheader = $('#topface'); // fixed容器
 3         // console.log(fixedheader);
 4         var wintop=$(window).scrollTop(); // 已滾動卷去的高度
 5         //console.log(wintop);
 6         let winHeight = $(window).height(); // 可視窗口的高度
 7         //console.log(winHeight);
 8         // 卷去一個可視窗口高度后執行
 9         /* if (wintop - winHeight > 0) {
10             // fixedheader.hide();
11             $fixedheader.addClass("showtopface");
12         } else {
13             // fixedheader.show();
14             $fixedheader.removeClass("showtopface");
15         } */
16         // 當滾動條離頂部100像素時的條件判斷和執行動作
17         if(wintop>100){
18             // fixedheader.hide();
19             $fixedheader.addClass("showtopface");
20         } else {
21             // fixedheader.show();
22             $fixedheader.removeClass("showtopface");
23         }
24 
25     })

通過上邊代碼,在做前端滾動條的控制時,或者滾動條滾動到離頂部指定位置高度時觸發某些動作。我這邊是當滾動到離頂部100時,給html標簽增加樣式showtopface,否則移除html標簽樣式showtopface

 


免責聲明!

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



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