Javascript實現頁面滾動時導航智能定位,javascript導航
常見的開發頁面中可能會有這麼一個需求,頁面中會有多個模組,每個模組對應一個導航,當頁面滾動到某個模組時,對應的模組導航需要加上一個類用於區分目前使用者所瀏覽地區。
假設結構如下:
<div class="container"> <div class="wrapper"> <div class="section" id="section1">section1</div> <div class="section" id="section2">section2</div> <div class="section" id="section3">section3</div> <div class="section" id="section4">section4</div> <div class="section" id="section5">section5</div> </div> <nav> <a href="#section1" rel="external nofollow" class="current">section1</a> <a href="#section2" rel="external nofollow" >section2</a> <a href="#section3" rel="external nofollow" >section3</a> <a href="#section4" rel="external nofollow" >section4</a> <a href="#section5" rel="external nofollow" >section5</a> </nav></div>
頁面滾動時導航定位
js代碼如下:
var $navs = $('nav a'), // 導航 $sections = $('.section'), // 模組 $window = $(window), navLength = $navs.length - 1; $window.on('scroll', function() { var scrollTop = $window.scrollTop(), len = navLength; for (; len > -1; len--) { var that = $sections.eq(len); if (scrollTop >= that.offset().top) { $navs.removeClass('current').eq(len).addClass('current'); break; } }});
效果如下:
不難看出,基本原理就是在window滾動的時候,依次將模組從後向前遍曆,如果window的滾動高度大於或等於當前模組的距頁面頂部的距離,則將當前模組對應的導航反白,並且不再繼續遍曆
點擊導航定位頁面
除了這種需求外,還有另一種需求,就是點擊導航定位到導航所對應模組的頂部。
代碼如下:
$navs.on('click', function(e) { e.preventDefault(); $('html, body').animate({ 'scrollTop': $($(this).attr('href')).offset().top }, 400);});
效果如下:
以上基本上滿足了業務的基本需求,這是工作中總結的經驗,希望對大家的學習有所協助,也希望大家多多支援幫客之家。