繁体   English   中英

添加和删​​除类到jquery onscroll

[英]Add and remove class to jquery onscroll

我需要在滚动时为标题添加一个“固定”类,并在以下脚本中向后滚动时删除它,但不确定如何最好地执行此操作:

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

想法赞赏。

add / remove类方法效果很好。

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

这是一个小提琴,展示它是如何工作的: http//jsfiddle.net/gisheri/RpPEe/413/

我已经翻译你的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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM