垂直菜单固定活动类

时间:2013-07-30 18:24:48

标签: jquery scroll

我的页面上有一个垂直菜单,链接到页面上的节元素。我要做的是在元素滚动到的时候以及当页面顶部到达页面顶部时给li一个'活动'类。

所有这一切都运行正常 - 但是,页面上的最后一个部分元素永远不会到达顶部,因此类活动保留在前一个元素上。

滚动到?

时,如何使最后一个元素成为活动类?

菜单:

<ul class="program-list">
<li class="program-list program-menu-item menu-item-toddlers">Toddlers</li>
<li class="program-list program-menu-item menu-item-elementry">Elementry</li>
<li class="program-list program-menu-item menu-item-preschool">Preschool</li>
<li class="program-list program-menu-item menu-item-adults">Adults</li>
</ul>

jquery

<script type="text/javascript">
     jQuery(window).scroll(function(){
                    var scrollTop = jQuery(window).scrollTop();
                    var programTop = jQuery('#programs').offset().top;
                    if(scrollTop >= programTop) {jQuery('ul.program-list li').removeClass('active');} 

                    var toddlersTop = jQuery('#toddlers').offset().top - 10;
                    var elementryTop = jQuery('#elementry').offset().top - 10;
                    var preschoolTop = jQuery('#preschool').offset().top - 10;
                    var adultsTop = jQuery('#adults').offset().top - 10;

                    if(scrollTop >= toddlersTop) {jQuery('ul.program-list li').removeClass('active'); jQuery('li.menu-item-toddlers').addClass('active');}
                    if(scrollTop >= elementryTop){jQuery('ul.program-list li').removeClass('active'); jQuery('li.menu-item-elementry').addClass('active');}
                    if(scrollTop >= preschoolTop){jQuery('ul.program-list li').removeClass('active'); jQuery('li.menu-item-preschool').addClass('active');}
                    if(scrollTop >= adultsTop){jQuery('ul.program-list li').removeClass('active'); jQuery('li.menu-item-adults').addClass('active');}
 });
    </script>

2 个答案:

答案 0 :(得分:1)

当您将页面滚动到结尾时,此代码将adults设置为活动状态:

if (scrollTop == jQuery(document).height() - jQuery(window).height())
    {jQuery('ul.program-list li').removeClass('active'); jQuery('li.menu-item-adults').addClass('active');}

答案 1 :(得分:0)

您可以尝试在底部放置一些东西(底部边距可能有用)或

//html
    <ul class="program-list">
    <li class="program-list program-menu-item menu-item-toddlers">Toddlers</li>
    <li class="program-list program-menu-item menu-item-elementry">Elementry</li>
    <li class="program-list program-menu-item menu-item-preschool">Preschool</li>
    <li class="program-list program-menu-item menu-item-adults">Adults</li>
    <li class="menu-item-x"></li>    
    </ul>



//css
    .menu-item-x
    {
    list-style-type:none;
    }