jquery - 手动滚动添加类在这里不起作用

标签 jquery html css

这是 JSFiddle 链接: http://jsfiddle.net/asif097/HHEqx/

你好,

在上面的链接中,您会发现单击链接时,active 类将添加到 ('.nav-inner a'),同时页面也会滚动。 (更多理解见代码):

$(document).ready(function() {

    $('html, body').animate({
            scrollTop: $(".target1").offset().top
    }, 1000);

    $('#link1').click(function() {
        $('html, body').animate({
            scrollTop: $(".target1").offset().top
        }, 1000);
        $('.nav-inner a').removeClass("active");
        $(this).addClass("active");
    });
    $('#link2').click(function() {
        $('html, body').animate({
            scrollTop: $(".target2").offset().top,
        }, 1000);
        $('.nav-inner a').removeClass("active");
        $(this).addClass("active");
    });
    $('#link3').click(function() {
        $('html, body').animate({
            scrollTop: $(".target3").offset().top
        }, 1000);
        $('.nav-inner a').removeClass("active");
        $(this).addClass("active");
    });

});

现在 当我手动滚动 addClass() 以相同的方式运行时,我希望发生这种情况。试过这个:

    $('html, body').scroll(function ()
{
    if(($('html, body').scrollTop())<1000)
    {
        $(".nav-inner a").removeClass('active');
        $(".nav-inner a:nth-child(1)").addClass('active');
    }
    else if(($('html, body').scrollTop())<2000)
    {
        $(".nav-inner a").removeClass('active');
        $(".nav-inner a:nth-child(2)").addClass('active');
    }
    else
    {
        $(".nav-inner a").removeClass('active');
        $(".nav-inner a:nth-child(3)").addClass('active');
    }
});

但是,不起作用。任何人都可以修复我的代码吗? (需要解释)

谢谢。

最佳答案

http://jsfiddle.net/HHEqx/4/

$(window).scroll(function (){
    var scrll = $(this).scrollTop();
    if(scrll < 1000)
    {
        $(".nav-inner a").removeClass('active');
        $(".nav-inner a:nth-child(1)").addClass('active');
    }
    else if(scrll < 2000)
    {
        $(".nav-inner a").removeClass('active');
        $(".nav-inner a:nth-child(2)").addClass('active');
    }
    else
    {
        $(".nav-inner a").removeClass('active');
        $(".nav-inner a:nth-child(3)").addClass('active');
    }
});

关于jquery - 手动滚动添加类在这里不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14908908/

相关文章:

css - 顶部 : 50% Does Nothing

javascript - 创建在单击另一个对象时隐藏的跨度

html - 使用 CSS 在子菜单下拉菜单下创建子菜单

javascript - 检查是否启用全屏、跨浏览器

html - 使用 xsl :if doesn't include closing tag

css - Navbar 的居中组件

javascript - 返回 false 或 e.preventdefault 不起作用

javascript - 如何拆分逗号分隔的字符串并使用javascript插入到html中

jquery - 如何限制 Lightbox 2 中的图像大小

html - CSS : Bad Gray Line to the side of the Navigation Bar on my Website