使用 JavaScript/JQuery 使导航链接在相关元素通过其下方时突出显示? [英] Making navigation links highlight when relevant element passes underneath it, using JavaScript/JQuery?

查看:24
本文介绍了使用 JavaScript/JQuery 使导航链接在相关元素通过其下方时突出显示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

When I click a link from the navigation menu the page scrolls to the appropriate section using this 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');
});

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

What I'd like to happen is when I manually scroll the page $(window).scroll(function(){...});, relevant to the section passing under the navigation menu #navi-container, the navigation link highlights using .addClass('activeNav');

推荐答案

看看我几天前偶然发现的这个 jsfiddle,我相信这正是你要找的:http://jsfiddle.net/x3V6Y/

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

我想指出的是,如果您最终使用它,您会重新考虑 for(i in Sections) 循环,因为它对性能造成了很大的影响.如果可以,最好使用这种循环:

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).

这篇关于使用 JavaScript/JQuery 使导航链接在相关元素通过其下方时突出显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆