修复了滚动时导航闪烁的问题 [英] Fixed nav flickers when scrolling

查看:92
本文介绍了修复了滚动时导航闪烁的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个导航栏,该导航栏距离页面顶部向下500px,但是一旦向下滚动,它就会固定在顶部,

I am trying to create a nav bar that is down 500px from the top of the page, but once you scroll down to it, it becomes fixed at the top, like this

最初我有以下代码:

$(window).scroll(function() {
    if ($(document).scrollTop() > 500) {
        $nav.addClass('fixed');
    }
    else {
        $nav.removeClass('fixed');
    }
});

.fixed {
    position: fixed;
    top: 0;
    z-index: 1;
}

但是,我的页面具有响应能力,导航栏不会始终位于页面下方500px.因此,当滚动到达导航栏的顶部时,我使用了.offset().top来触发固定的类.

However, my page is responsive and the nav bar will not always be 500px down the page. Therefore, I used .offset().top to trigger the fixed class when scrolling reaches the top of my nav bar.

$(window).scroll(function() {
    var $navTop = $nav.offset().top;
    if ($(document).scrollTop() > $navTop) {
        $nav.addClass('fixed');
    }
    else {
        $nav.removeClass('fixed');
    }
});

问题在于,滚动时导航栏会非常闪烁.我尝试用.position()替换.offset(),这消除了闪烁,但是它使导航栏固定的时间长于向上滚动到其原始位置时所需的时间.请帮忙!

The issue is that the nav bar flickers terribly when you scroll. I tried replacing .offset() with .position(), which gets rid of the flicker, but it keeps the nav bar fixed for longer than it should when scrolling back up past its original position. Please, help!

推荐答案

我在计算机(chrome& mac)上没有看到此问题,但我有一个可能的猜测.

I don't see the issue on my computer (chrome & mac) but I have a likely guess.

我的猜测是,这是由与布局颠簸相似的原因引起的.即使不更改状态,添加/删除类也非常麻烦.由于您正在读取DOM的偏移量,然后在每个滚动刻度(每秒数次)上设置一个类/删除一个类,所以这可能是闪烁的原因.

My guess is that this is caused by something similar to layout thrashing. It is super gross to be adding / removing the class even if it isn't changing state. Since you are reading the offset from the DOM, and then setting a class / removing a class on every scroll tick (tons of times a second), this would be a likely cause of flicker.

这篇关于修复了滚动时导航闪烁的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆