Highlight active link when using scrollto based on current view

爱⌒轻易说出口 提交于 2019-12-18 01:10:51

问题


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?


回答1:


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/



来源:https://stackoverflow.com/questions/8393442/highlight-active-link-when-using-scrollto-based-on-current-view

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!