国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > JavaScript > 正文

Javascript實(shí)現(xiàn)頁(yè)面滾動(dòng)時(shí)導(dǎo)航智能定位

2019-11-19 16:39:16
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

常見的開發(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)。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 吐鲁番市| 海林市| 绥棱县| 响水县| 大丰市| 岱山县| 碌曲县| 武川县| 广丰县| 南丰县| 城口县| 丰宁| 伽师县| 博湖县| 乌鲁木齐县| 大关县| 南宁市| 中山市| 广宁县| 平和县| 灵璧县| 青海省| 开封县| 克东县| 崇信县| 静安区| 绥阳县| 绥化市| 会同县| 双江| 珲春市| 桑日县| 台湾省| 会宁县| 汪清县| 临西县| 于田县| 昆明市| 衡东县| 绍兴市| 徐水县|