Making navigation links highlight when relevant element passes underneath it, using JavaScript/JQuery?

后端 未结 2 919
伪装坚强ぢ
伪装坚强ぢ 2021-02-09 03:42

I have a single page website with the navigation menu position:fixed at the top of the page.

When I click a link from the navigation menu the page scrolls

2条回答
  •  无人及你
    2021-02-09 04:21

    Check-out this jsfiddle I stumbled across a few days ago, I believe it's just what you're looking for: http://jsfiddle.net/x3V6Y/

    $(function(){
        var sections = {},
            _height  = $(window).height(),
            i        = 0;
    
        // Grab positions of our sections
        $('.section').each(function(){
            sections[this.name] = $(this).offset().top;
        });
    
        $(document).scroll(function(){
            var $this   = $(this),
                pos     = $this.scrollTop(),
                $parent = {};
    
            for(i in sections){
                $parent = $('[name="' + i + '"]').parent();
                //you now have a reference to a jQuery object that is the parent of this section
    
                if(sections[i] > pos && sections[i] < pos + _height){
                    $('a').removeClass('active');
                    $('#nav_' + i).addClass('active');
                }  
            }
        });
    });
    

    I would like to note that if you end-up using this that you re-think the for(i in sections) loop as it is a big hit to performance. If you can, it is an excellent idea to use this kind of loop:

    for (var i = 0, len = sections.length; i < len; i++) {
        //...
    }
    

    ...but that requires a re-think of how to store the offsets of the section elements since this type of loop requires an array rather than an object (an object will work but it has to be zero-indexed and all the indexes have to be integers).

提交回复
热议问题