使用offsetHeight(Javascript)添加CSS类会导致元素 Flink

qcuzuvrc  于 2023-03-16  发布在  Java
关注(0)|答案(2)|浏览(101)

我已重新创建问题的简化工作版本:一个小横幅(当用户向下滚动时隐藏),主导航(当用户向下滚动时应该粘在页面顶部)和一些虚拟内容,使滚动成为可能。
当滚动位置小于或等于main-nav高度时,我通过向瘦横幅(display: none)添加类sb-scrolling来实现当前的实现。
然而,当滚动缓慢,有一个 Flink ,似乎是隐藏和显示瘦横幅。谁能指导我哪里出错了?

const skinnyBanner = document.querySelector('.skinny-banner');
      const mainNav = document.querySelector('.main-nav');

      // Handle page scroll
      let scrollpos = window.scrollY;
      const navHeight = mainNav.offsetHeight;

      window.addEventListener('scroll', function() {
        scrollpos = window.scrollY;

        if (scrollpos >= navHeight) {
          mainNav.classList.add('scrolling');
          skinnyBanner.classList.add('sb-scrolling');
        } else {
          mainNav.classList.remove('scrolling');
          skinnyBanner.classList.remove('sb-scrolling');
        }
      });
header {
  display: block;
  position: sticky;
  top: 0;
}

.skinny-banner {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: lightgrey;
  width: 100%;
  height: 40px;
}

.main-nav {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: yellow;
  width: 100%;
  height: 140px;
}

.skinny-nav-menu {
  display: flex;
  gap: 24px;
}

.sb-scrolling {
  display: none !important;
}

.scrolling {
  min-height: 70px !important;
}

.content-block-1 {
  height: 300px;
  background-color: orange;
  display: flex;
  align-items: center;
  justify-content: center;
}

.content-block-2 {
  height: 300px;
  background-color: lightblue;
  display: flex;
  align-items: center;
  justify-content: center;
}

.content-block-3 {
  height: 300px;
  background-color: lightcyan;
  display: flex;
  align-items: center;
  justify-content: center;
}
<header>
  <nav>
    <div class="skinny-banner">SKINNY BANNER THAT IS HIDDEN WHEN SCROLLING DOWN</div>
    <div class="main-nav">
    MAIN NAVIGATION THAT SHOULD ALWAYS BE VISIBLE
    </div>
  </nav>
</header>

<div class="content-block-1">RANDOM PAGE CONTENT</div>
<div class="content-block-2">RANDOM PAGE CONTENT</div>
<div class="content-block-3">RANDOM PAGE CONTENT</div>
wswtfjt7

wswtfjt71#

问题是因为

.sb-scrolling {
  display: none !important;
}

它只是在div添加到div时使其消失,因此您可以看到 Flink 效果。
x一个一个一个一个x一个一个二个一个x一个一个三个一个

cwtwac6a

cwtwac6a2#

如果将banner的display属性设置为none,它将从DOM流中消失,因此会更改scrollpos值(将其降低到低于阈值navHeight),从而使banner再次出现并重新开始。
如果你只是想在向下滚动时隐藏横幅,并且不想让它再次出现,只需将navHeight设置为-1scrollpos〉navHeight。

相关问题