简体   繁体   English

粘页眉滚动功能异常

[英]Sticky Header Scroll misfunction

I've got following code for my Header that gets sticky if it reaches the top of the window: 我的Header有以下代码,如果到达窗口顶部,该代码会发粘:

$(function () {
    var stickyHeaderTop = $('#outer-header').offset().top;

    $(window).scroll(function () {
        if ($(window).scrollTop() > stickyHeaderTop) {
            $('#outer-header').css({
                position: 'fixed',
                top: '-300px'
            });
        } else {
            $('#outer-header').css({
                position: 'static',
                top: '0px'
            });
        }
    });
});

It works, but as it reaches the top and gets sticky the content scrolls the normal scroll + the height of the div that was over the Header.(so it makes a too big jump that doesn't look smooth) 它可以工作,但是当它到达顶部并变得发粘时,内容将滚动正常滚动+超过Header的div的高度(因此它会跳得太大,看起来不太平滑)

Thanks to CBroe for his hint! 感谢CBroe的提示! This is a working solution: 这是一个可行的解决方案:

$(function () {
    var stickyHeaderTop = $('#outer-header').offset().top;

    $(window).scroll(function () {
        if ($(window).scrollTop() >= stickyHeaderTop) {
            $('#outer-header').css({
                position: 'fixed',
                top: '-300px'
            });
            $('#main').css({
                position: 'relative',
                top: '332px'
            });
        } else {
            $('#outer-header').css({
                position: 'absolute',
                top: '0px'
            });
            $('#main').css({
                position: 'relative',
                top: '332px'
            });
        }
    });
});

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

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