用jquery實現樓層滾動對應導航高亮


html 結構排版:

// 定位到頁面左側或者右側

<div class="nav"> 

       <ul id="menu-list">

            <li><a href="#one" class="links one">Menu 1</a></li>

            <li><a href="#two" class="links two">Menu 2</a></li>
            <li><a href="#three" class="links three">Menu 3</a></li>
            <li><a href="#four" class="links four">Menu 4</a></li>
            <li><a href="#five" class="links five">Menu 5</a></li>
            <li><a href="#six" class="links six">Menu 6</a></li>
       </ul>
</div>

 

// 頁面頂部的其它內容塊

<div class="other-content"> 這里是其它的內容,假設內容高度為300px</div>

//  頁面與導航對應的內容塊
<div id="wrapper">
       <div id="one" class="container">one</div>
       <div id="two" class="container">two</div>
       <div id="three" class="container">three</div>
       <div id="four" class="container">four</div>
       <div id="five" class="container">five</div>
       <div id="six" class="container">six</div>
</div>

 js效果實現:

<script>

      /*
         菜單-內容塊 對應

        利用錨點鏈接的原理,所以導航的a標簽的href= # + 對應內容塊的ID
        為了設置對應導航高亮,為了方便起見,導航的class需要與對應內容塊的ID保持一致
        如果樓層上面有頭部等其他內容需要判斷currentScroll 的值是否大於上面其它內容塊的高度,否則執行這一步(var id = $currentSection.attr('id'))的時候 會報錯
     */

     
      $(window).scroll(function(){

           var $sections = $('.container'); // 獲取所有的內容塊
           var currentScroll = $(this).scrollTop();  // winodw滾動的高度
           var $currentSection ;   //   當前內容塊
         $sections.each(function(){
            var divPosition = $(this).offset().top;  // 獲取到當前內容塊具體頁面頂部的距離
            if( divPosition - 1 < currentScroll){  //  通過條件判斷匹配到當前滾動內容塊
               $currentSection = $(this);
            }

    // 如果樓層最上端有其它的內容快需要加一個判斷

    if(currentScroll > 300){

       var id = $currentSection.attr('id');
                 $('.links').removeClass('menu-active');
                 $("."+id).addClass('menu-active');

    }
            

         })

    });

</script>

 

 

文章來源:http://caibaojian.com/higlight-nav-link.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM