在创建一个粘滞的导航栏时,我注意到一个奇怪的错误,该导航栏应该在滚动上设置动画,降低其高度.

当滚动较小时(例如,只在向下箭头键上轻击一次),导航就会反弹,因为脚本似乎返回0表示滚动.

以下是代码:

window.onscroll = function() {
  var scrollDiv = document.getElementById('dojo-nav');
  if (window.scrollY > 0) {
    scrollDiv.style.height = '50px';
  } else {
    scrollDiv.style.height = '200px';
  }
};
body {
  margin: 0;
}

#dojo-nav {
  transition: all 0.2s ease-in;
}
<div id="dojo-nav" style="position:sticky;top:0px;background: violet;height: 200px;"></div>
<div style="height:50vh;background-color: cyan;"></div>
<div style="height:100vh;background-color: orange;"></div>

有没有人可以在不设置固定位置和导航杆间隔或相同高度的情况下解决这个问题?

推荐答案

sticky在这里不起作用,因为粘性DIV的高度改变了window.scrollY.

fixed,window.scrollY是稳定的,因此没有抖动.

另外,您不需要在JS中设置样式,可以使用一个css变量来动态更改css规则值:

 window.onscroll = () => document.body.classList.toggle('collapsed-nav', window.scrollY > 0);
body {
  --navbar-height: 200px;
  margin: 0px;
}

body.collapsed-nav{
  --navbar-height: 50px;
}

#dojo-nav {
  transition: all 0.2s ease-in;
  position:fixed;
  width:100%;
  background: violet;
  height: var(--navbar-height);
}

#content {
  padding-top: var(--navbar-height);  
  transition: all 0.2s ease-in;
  height: 50vh;
  background-color: cyan;
}

#footer {
  height:100vh;
  background-color: orange;
}
<div id="dojo-nav"></div>
<div id="content"></div>
<div id="footer"></div>

Css相关问答推荐

寻找组件中最大的元素来设置其他组件的高度

CSS Grid我不想要的东西

不明白为什么 div 不均匀并且不填满页面

TypeScript 中有效的 CSS 属性名称数组,但带有连字符

如何使用 ReactJS 使用 CSS 设置 map 容器的样式

为什么每次加载新页面时我的 React 侧边栏都会抖动?

如何在 Tailwind 中使用 `margin: y x;` 速记?

CSS 字符串变量的正确null值是多少?

我怎样才能让这个边框出现在按钮元素的上方?

flex-start 和基线有什么区别?

CSS nth-child 表示大于和小于

更改最后一个
  • 的 CSS
  • bootstrap 模式对话框中的谷歌 map 自动完成结果

    定位背景图片,添加内边距

    矩形图像的 CSS 圆形裁剪

    弹性框中的边距折叠

    我应该使用最大设备宽度还是最大宽度?

    为什么是垂直对齐:文本顶部;不能在 CSS 中工作

    如何在 React 应用程序中使用 CSS 模块应用全局样式?

    CSS中伪元素前的&是什么意思?