用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

posted @ 2017-10-12 10:51  *小七儿*  阅读(4698)  评论(0编辑  收藏  举报