添加和删​​除类到jquery onscroll

时间:2014-03-13 16:18:13

标签: javascript jquery

我需要在滚动时为the header添加一个“固定”类,并在以下脚本中向上滚动时将其删除,但不确定如何做到最好:

<script>
    $(document).ready(function () {
        var div = $('.header');
        var div2 = $('.headerPlaceholder');
        var start = $(div).offset().top;

        $.event.add(window, "scroll", function () {
            var p = $(window).scrollTop();
            $(div).css('position', ((p) > start) ? 'fixed' : 'static');
            $(div).css('top', ((p) > start) ? '0px' : '');
            $(div2).css('display', ((p) > start) ? 'block' : 'none');
        });

    });
</script>

这会停止在每次向下滚动后触发事件,这是现在脚本中指定的CSS所发生的事情,因此我需要添加一个类。

CSS:

.fixed {
position: fixed;
}

赞赏的想法。

2 个答案:

答案 0 :(得分:1)

添加/删除类方法效果很好。

$(document).ready(function () {
    $(window).scroll(function () {
        if ($(this).scrollTop() > 100) {
            $('.header').addClass("fixed");
        } else {
            $('.header').removeClass("fixed");
        }
    });
});

这是一个显示其工作原理的小提琴:http://jsfiddle.net/gisheri/RpPEe/413/

答案 1 :(得分:1)

我已经将你的js翻译为使用css,将1类的应用程序用于正文

$(document).ready(function () {
    var start = $('.header').offset().top;

    $.event.add(window, "scroll", function () {
        var p = $(window).scrollTop();
        if( p > start ) {
            $('body').addClass('fixed');
        } else {
            $('body').removeClass('fixed');
        }
    });
});

CSS

body.fixed .header {
    position: fixed;
    top: 0;
}
body.fixed .headerPlaceholder {
    display: block;
}
相关问题