基于当前视图使用scrollto时突出显示活动链接

时间:2011-12-05 23:33:59

标签: jquery scrollto

我有一个网页是一个页面,用户使用使用scrollto jquery插件的链接导航到每个部分。

我的问题是:我想在主菜单中显示活动链接。因此,如果您滚动到联系表单,则会突出显示联系人链接。现在,我可以通过在单击后添加类来在jquery中执行此操作。如果这样做,如果用户要手动滚动到另一个部分,联系人链接仍然是活动的,这将是不正确和误导。

所以我的想法是以某种方式解决当前正在查看哪个div id。我真的不明白怎么做。有任何想法吗?

1 个答案:

答案 0 :(得分:20)

这应该可以让您添加手动滚动覆盖:

$(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');
            }  
        }
    });
});

演示:http://jsfiddle.net/x3V6Y/

相关问题