使用JavaScript/JQuery,当相关元素在其下面传递时,使导航链接突出显示?

Nas*_*sir 8 javascript jquery

我有一个单页网站,页面position:fixed顶部有导航菜单.

当我单击导航菜单中的链接时,页面将使用此JQuery滚动到相应的部分:

$('a[href^="#"]').live('click',function(event){
     event.preventDefault();
     var target_offset = $(this.hash).offset() ? $(this.hash).offset().top : 0;
     $('html, body').animate({scrollTop:target_offset}, 1200, 'easeOutExpo');
});
Run Code Online (Sandbox Code Playgroud)

我想要发生的是当我手动滚动页面时$(window).scroll(function(){...});,与导航菜单下面的部分相关#navi-container,导航链接突出显示使用.addClass('activeNav');

Jas*_*per 6

几天前我偶然发现了这个jsfiddle,我相信这正是你要找的: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');
            }  
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

我想要指出的是,如果你最终使用它,你会重新思考for(i in sections)循环,因为它对性能有很大影响.如果可以的话,使用这种循环是一个很好的主意:

for (var i = 0, len = sections.length; i < len; i++) {
    //...
}
Run Code Online (Sandbox Code Playgroud)

...但是这需要重新考虑如何存储节元素的偏移量,因为这种类型的循环需要一个数组而不是一个对象(一个对象可以工作但它必须是零索引的并且所有索引都有是整数).