You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现滚动时高度可变的固定header

实现思路

核心逻辑是通过监听页面滚动事件动态切换header的样式类,配合CSS过渡实现高度平滑变化,整体实现成本很低:

  • 先给header写默认状态的样式,固定定位+初始高度40px,同时加高度变化的过渡动画
  • 写一个滚动后触发的样式类,定义高度为30px
  • 监听页面滚动事件,当页面纵向滚动距离大于0时给header加上述样式类,回到顶部时移除即可
完整代码示例

HTML

<header class="fixed-header">站点Header内容</header>
<!-- 页面其他内容,用来撑出滚动条 -->
<main style="height: 200vh; padding-top: 40px;">
  页面内容区域
</main>

这里给main加初始padding-top是为了避免固定定位的header挡住页面顶部内容,padding值和header初始高度保持一致即可。

CSS

.fixed-header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 40px;
  line-height: 40px; /* 让文字垂直居中 */
  background: #fff;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  /* 高度变化加过渡,更丝滑 */
  transition: height 0.3s ease, line-height 0.3s ease;
  z-index: 999;
}

/* 滚动后激活的类 */
.fixed-header.scrolled {
  height: 30px;
  line-height: 30px;
}

JavaScript

const header = document.querySelector('.fixed-header');

window.addEventListener('scroll', () => {
  // 滚动距离大于0就加scrolled类
  if (window.scrollY > 0) {
    header.classList.add('scrolled');
  } else {
    header.classList.remove('scrolled');
  }
});

// 如果需要优化滚动事件触发频率,可以加节流函数,比如:
// function throttle(func, delay = 100) {
//   let timer = null;
//   return function(...args) {
//     if (!timer) {
//       timer = setTimeout(() => {
//         func.apply(this, args);
//         timer = null;
//       }, delay);
//     }
//   }
// }
// window.addEventListener('scroll', throttle(() => {
//   上述滚动逻辑
// }));
额外优化提示
  • 如果header内部有其他元素(比如logo、导航),可以同时在.scrolled类下调整这些元素的大小、边距,适配缩小后的header高度
  • 要是不需要过渡动画,删掉CSS里的transition属性即可,高度会直接切换

内容的提问来源于stack exchange,提问作者jonhdoe420

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 06:24:04