今天利用空閑時間,研究了一下瀏覽器滾動條的簡單控制,主要是通過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
