滚动时出现Jquery addClass

时间:2014-04-09 15:29:48

标签: jquery scroll addclass

我有这段代码,但出于某种原因,' addClass函数'它不适用于活跃的' li'元素,一切正常(点击和滚动功能)解决了这个问题。有什么提示吗?

HTML:

<div id="wrapper">

    <nav>
        <ul>
            <li>
                section1
            </li>
            <li>
                section2
            </li>
            <li>
                section3
            </li>
            <li>
                section4
            </li>
        </ul>
    </nav>

    <div id ="section1">
        <p>vccvfcwec</p>
    </div>

    <div id ="section2">
        <p>vccvfcwec</p>
    </div>

    <div id ="section3">
        <p>vccvfcwec</p>
    </div>

    <div id ="section4">
        <p>vccvfcwec</p>
    </div>

</div>

jQuery的:

$('ul li:eq(0)').click(function() {
    $('html, body').animate({
        scrollTop: $("#section4").offset().top
    }, 1500);
});
$('ul li:eq(1)').click(function() {
    $('html, body').stop().animate({
        scrollTop: $("#section3").offset().top
    }, 1500);
});
$('ul li:eq(2)').click(function() {
    $('html, body').stop().animate({
        scrollTop: $("#section2").offset().top
    }, 1500);
});
$('ul li:eq(3)').click(function() {
    $('html, body').stop().animate({
        scrollTop: $("#section1").offset().top
    }, 1500);
});

var section1Height = $('#section1').height();
var section2Height = $('#section2').height();
var section3Height = $('#section3').height();
var section4Height = $('#section4').height();

$(window).scroll(function() {
    var winTop = $(window).scrollTop();

    if(winTop >= section1Height && winTop <= section2Height){
        $('ul li:eq(0)').addClass('active').not().removeClass('active');
    }
    else if(winTop >= section2Height && winTop <= section3Height){
        $('ul li:eq(1)').addClass('active').not().removeClass('active');
    } 
    else if(winTop >= section3Height && winTop <= section4Height){
        $('ul li:eq(2)').addClass('active').not().removeClass('active');
    }
    else if(winTop >= section4Height){
        $('ul li:eq(3)').addClass('active').not().removeClass('active');
    }
});

CSS:

.active {
    color:yellow !important;
    background-color: #FFF !important;
}

0 个答案:

没有答案