常見的開發(fā)頁(yè)面中可能會(huì)有這么一個(gè)需求,頁(yè)面中會(huì)有多個(gè)模塊,每個(gè)模塊對(duì)應(yīng)一個(gè)導(dǎo)航,當(dāng)頁(yè)面滾動(dòng)到某個(gè)模塊時(shí),對(duì)應(yīng)的模塊導(dǎo)航需要加上一個(gè)類用于區(qū)分當(dāng)前用戶所瀏覽區(qū)域。
假設(shè)結(jié)構(gòu)如下:
<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>
頁(yè)面滾動(dòng)時(shí)導(dǎo)航定位
js代碼如下:
var $navs = $('nav a'), // 導(dǎo)航 $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滾動(dòng)的時(shí)候,依次將模塊從后向前遍歷,如果window的滾動(dòng)高度大于或等于當(dāng)前模塊的距頁(yè)面頂部的距離,則將當(dāng)前模塊對(duì)應(yīng)的導(dǎo)航突出顯示,并且不再繼續(xù)遍歷
點(diǎn)擊導(dǎo)航定位頁(yè)面
除了這種需求外,還有另一種需求,就是點(diǎn)擊導(dǎo)航定位到導(dǎo)航所對(duì)應(yīng)模塊的頂部。
代碼如下:
$navs.on('click', function(e) { e.preventDefault(); $('html, body').animate({ 'scrollTop': $($(this).attr('href')).offset().top }, 400);});效果如下:

以上基本上滿足了業(yè)務(wù)的基本需求,這是工作中總結(jié)的經(jīng)驗(yàn),希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注