遇到的問題:
在做官網的時候,需要滾動定位的區塊的圖片不確定,無法確定用戶瀏覽區域對應的模塊導航
之前的解決方案是:
通過定位滾動條的位置來判斷用戶瀏覽區域對應的模塊導航,這種方法的弊端是,區塊的高度不確定時就無法計算滾動條的位置來判斷;
優化方案:
頁面中會有多個模塊,每個模塊對應一個導航,當頁面滾動到某個模塊時,對應的模塊導航需要加上一個類用於區分當前用戶所瀏覽區域。
以下是DEMO
<!-- html -->
<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>
<script> <!-- 頁面滾動時導航定位 --> 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; } } }); <!-- 點擊導航定位頁面 --> $navs.on('click', function(e) { e.preventDefault(); $('html, body').animate({ 'scrollTop': $($(this).attr('href')).offset().top }, 400); }); </script>
write by tuantuan