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

为何使用JavaScript实现的header滚动高度变化动画无法生效?

问题原因

你的代码里CSS给header设置了min-height: 12vh,当JS尝试设置height: 50px时,如果50px小于12vh的实际像素值,min-height会强制header保持不低于12vh的高度,导致视觉上看不到变化。而console能输出,说明滚动事件和条件判断是正常工作的。

解决方案

有三种常用修复方式:

方式1:把CSS的min-height替换为height

直接修改header的CSS属性,让JS设置的height能覆盖默认样式:

header {
  display: flex;
  background-color: var(--color3);
  flex-direction: row;
  padding: 0px 120px;
  height: 12vh; /* 替换min-height为height */
  align-items: center;
  justify-content: space-between;
  width: 100%;
  margin: 0 auto;
  position: fixed;
  font-family: var(--titleFont);
  top: 0;
  z-index: 10;
  transition: height 0.3s ease; /* 可选:添加过渡动画让高度变化更平滑 */
}

方式2:JS中同步修改min-height

如果需要保留min-height的特性(比如header内容过多时自动撑开),可以在JS里同时设置height和min-height:

window.onload = () => {
  const header = document.querySelector("header");

  window.addEventListener("scroll", () => {
    if (window.scrollY > 50) {
      console.log("heeeeeeeey");
      header.style.height = "50px";
      header.style.minHeight = "50px"; // 同步修改min-height
    } else {
      header.style.height = "12vh";
      header.style.minHeight = "12vh"; // 恢复原min-height
    }
  });
};

方式3:用CSS类切换(推荐)

这种方式更符合样式与逻辑分离的原则,把样式规则放在CSS里,JS只负责切换类:

header {
  display: flex;
  background-color: var(--color3);
  flex-direction: row;
  padding: 0px 120px;
  min-height: 12vh;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  margin: 0 auto;
  position: fixed;
  font-family: var(--titleFont);
  top: 0;
  z-index: 10;
  transition: all 0.3s ease; /* 添加过渡动画 */
}

/* 滚动后的header样式类 */
header.scrolled {
  min-height: 50px;
  height: 50px;
}
window.onload = () => {
  const header = document.querySelector("header");

  window.addEventListener("scroll", () => {
    if (window.scrollY > 50) {
      console.log("heeeeeeeey");
      header.classList.add("scrolled");
    } else {
      header.classList.remove("scrolled");
    }
  });
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 19:10:32