Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
740 views
in Technique[技术] by (71.8m points)

jquery - Highlight active link when using scrollto based on current view

I have a website which is one page and the user navigates to each section using links which uses the scrollto jquery plugin.

My problem is: I want to show the active link in the main menu. So if you scroll to the contact form the contact link is highlighted. Now I could do this in jquery by adding the class after clicking. If done like that if a user was to manually scroll to another section the contact link would still be active, which would be incorrect and misleading.

So my thoughts would be to somehow work out which div id is currently in view. I don't really understand how to do that though. Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This should work for you to add the manual scrolling override:

$(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 pos = $(this).scrollTop();

        // Look in the sections object and see if any section is viewable on the screen. 
        // If two are viewable, the lower one will be the active one. 
        for(i in sections){
            if(sections[i] > pos && sections[i] < pos + _height){
                $('a').removeClass('active');
                $('#nav_' + i).addClass('active');
            }  
        }
    });
});

Demo: http://jsfiddle.net/x3V6Y/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...