jquery滚动,在页面滚动时更改导航活动类,相对于节

Jos*_*shc 12 jquery jsfiddle

http://jsfiddle.net/motocomdigital/gUWdJ/


我正在使用jquery滚动技术,我想适应我的项目.

请将我的项目示例视为小提琴http://jsfiddle.net/motocomdigital/gUWdJ/

目前,您可以看到我的导航链接会自动为相对于其的滚动设置动画<section>.

我的问题是,使用该$(window).scroll方法,当部分到达窗口顶部时,如何向我添加一个.activenav a

因此,例如,如果用户向下滚动页面(而不是导航链接),我希望活动类添加相对导航链接.指示您在页面上的位置.

每当我猜测用户向下滚动页面时,必须删除活动类,然后添加活动类.

此外,您还必须考虑固定导航栏的28px高度,偏移顶部窗口.


任何人都可以请给我一个技巧,我可以尝试使用或改编,或者可能让我使用我的jsfiddle :)


任何帮助将非常感谢,提前感谢!


http://jsfiddle.net/motocomdigital/gUWdJ/


在此输入图像描述

A. *_*lff 42

如果您希望更通用的功能:

看看演示

$(window).scroll(function() {
    var windscroll = $(window).scrollTop();
    if (windscroll >= 100) {
        $('nav').addClass('fixed');
        $('.wrapper section').each(function(i) {
            if ($(this).position().top <= windscroll - 100) {
                $('nav a.active').removeClass('active');
                $('nav a').eq(i).addClass('active');
            }
        });

    } else {

        $('nav').removeClass('fixed');
        $('nav a.active').removeClass('active');
        $('nav a:first').addClass('active');
    }

}).scroll();?
Run Code Online (Sandbox Code Playgroud)


Jai*_*Jai 7

你可以这样做:http://jsfiddle.net/gUWdJ/1/

$(window).scroll(function() {

    if ($(this).scrollTop() < $('section[data-anchor="top"]').offset().top) {
       $('nav a').removeClass('active');
    }

    if ($(this).scrollTop() >= $('section[data-anchor="top"]').offset().top) {
      $('nav a').removeClass('active');
      $('nav a:eq(0)').addClass('active');
    }
    if ($(this).scrollTop() >= $('section[data-anchor="news"]').offset().top) {
      $('nav a').removeClass('active');
      $('nav a:eq(1)').addClass('active');
    }
    if ($(this).scrollTop() >= $('section[data-anchor="products"]').offset().top) {
      $('nav a').removeClass('active');
      $('nav a:eq(2)').addClass('active');
    }
    if ($(this).scrollTop() >= $('section[data-anchor="contact"]').offset().top) {
      $('nav a').removeClass('active');
      $('nav a:eq(3)').addClass('active');
    }

});
Run Code Online (Sandbox Code Playgroud)