Javascript實現頁面滾動時導航智能定位,javascript導航

來源:互聯網
上載者:User

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);});

效果如下:

以上基本上滿足了業務的基本需求,這是工作中總結的經驗,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.