jquery scroll, change navigation active class as the page is scrolling, relative to sections

前端 未结 3 659
青春惊慌失措
青春惊慌失措 2020-11-29 21:33

http://jsfiddle.net/motocomdigital/gUWdJ/


I\'m after a jquery scroll technique please that I would like to adapt to my project.

Please see my

3条回答
  •  鱼传尺愫
    2020-11-29 21:47

    I went ahead and modified my script off of A. Wolf because I needed to make sure that my menu items lit up with a negative top difference instead of at 0. This works a lot better than creating a separate function and avoids having to create a click event for each menu item. I would also modify this script to account for the last item in the menu, it should be automatically highlighted if the second to last item is. I suppose mine is very similar but different as I handled my each loop outside of the my main highlight function. The other great thing about my modification is that accounts for having images inside of a link inside of a menu item and accounts for the height of a element and when the bottom of that element hits the top of the page, which is when the highlight should end before a new one does.

    function highlight(item)
    {
    var itemTop = jQuery(item).position().top;
    
    var windowTop = jQuery(window).scrollTop(); 
    var topDifference = (windowTop - itemTop); 
    
    var itemHeight = jQuery(item).height();
    var bottomDifference = topDifference - itemHeight; 
    
    var menuId = jQuery('#nav-icons li a').attr('href');
    if (menuId = item)
    {
        if(topDifference > -1 && bottomDifference < 0)
        {
            jQuery("#nav-icons li a[href='" + item + "']").parent().addClass('active');
            jQuery("#nav-icons li a[href!='" + item + "']").parent().removeClass('active');
        }
        else {
            jQuery("#nav-icons li a[href='" + item + "']").parent().removeClass('active');
        }
    }
    }
    jQuery('#nav-icons li a').each(function(){
    var eachAttr = jQuery(this).attr('href');
    highlight(eachAttr);
    });
    

提交回复
热议问题