如何修复尝试滚动时的闪烁效果

How to fix flicker effect when trying to scroll

本文关键字:闪烁 滚动 何修复      更新时间:2023-09-26

我有2个元素被设置为固定位置,如果他们到达页面底部的位置元素,然后设置回静态使用javascript

当我尝试通过单击滚动条并拖动它来滚动时,我有一个问题。如果你一直滚动到底部,然后如果你试着点击滚动条并把它拖上来。它闪烁并阻止我滚动。

这里是JSFiddle

<header>This is the header</header>
<main>
    <div id="content"></div>
    <section id="fixed-elements">
        <div id="fix1">Fixed Footer2</div>
        <div id="fix2">Fixed Footer1</div>
    </section>
</main>
<footer>This is the footer</footer>
Javascript

$(document).ready(function () {
$(window).scroll(function () {
    if ($(window).scrollTop() + $(window).height() == $(document).height()) {
        $('#fixed-elements').css({
            'position': 'static',
                'bottom': 'auto',
        });
    } else {
       $('#fixed-elements').css({
            'position': 'fixed',
                'bottom': '0',
        });            
    }
});
});
CSS

footer, header {
    background-color:green;
}
#content {
    height:1000px;
}
#fixed-elements {
    position:fixed;
    bottom:0;
    overflow:hidden;
}

这是怎么回事?我该怎么补救呢?(我认为当尝试使用鼠标中点击滚动时也会发生类似的情况)。

可以不使用静态,但使用重新计算的值bottom:

'bottom': $('footer').outerHeight(true) + (($('body').outerHeight(true) - $('body').outerHeight())/2),
http://jsfiddle.net/rbz16Lpp/

查看这个jsfield。它完成了你想要的没有闪烁。

基本上,一旦你滚动到页脚的顶部,它将#fixed-elements的位置设置为绝对的,相对于main的底部,position: relative

jQuery:

$(document).ready(function () {
    var totalHeight = $(document).height() - $(window).height(),
        footerHeight = $('footer').outerHeight();
    $(window).scroll(function () {
        console.log($(window).scrollTop(), (totalHeight - footerHeight));
        if ($(window).scrollTop() > (totalHeight - footerHeight)) {
            $('#fixed-elements').css({
                'position': 'absolute',
                 'bottom': 0
            });
        } else {
           $('#fixed-elements').css({
                'position': 'fixed',
                'bottom': 0
            });            
        }
    });
});

CSS(只添加了一行):

/* you might consider removing padding and margin from the body,
   because it'll make it a little smoother
body {
    margin: 0;
    padding: 0;
} */
main {
    position: relative; // added this to main
}
footer, header {
    background-color:green;
}
#content {
    height:1000px;
}
#fixed-elements {
    position:fixed;
    bottom:0;
}