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

如何实现向下滚动60px时显示第二个header?

解决方案

你的代码缺少滚动监听的JavaScript逻辑,同时存在HTML标签未闭合、初始状态未设置的问题,以下是完整修复方案:

1. 修正HTML标签错误

补全未闭合的<h1>标签,避免渲染异常,同时添加测试用的长内容方便滚动验证:

<!-- header2 -->
<nav class="nav-header2">
    <div class="header2-container">
        <h1>header2</h1>
    </div>
</nav>

<!-- header1 -->
<nav class="nav-header1">
    <div class="header1-container">
        <h1>header1</h1>
    </div>
</nav>

<!-- 测试滚动用的长内容 -->
<div style="height: 1500px; padding-top: 80px;">
    滚动测试内容...<br>
    继续向下滚动超过60px即可切换头部
</div>

2. 调整CSS样式

  • 初始隐藏header2
  • 给两个头部添加固定定位,确保始终在顶部显示
  • 给页面添加顶部内边距,避免内容被固定头部遮挡
/* 全局样式重置,消除默认边距影响 */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    padding-top: 60px; /* 预留头部高度空间 */
}

.nav-header2{
    background: purple;
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    top: 0;
    width: 100%;
    display: none; /* 初始状态隐藏 */
}
.header2-container{
    width: 68vw;
    height: 60px;
    padding: 0 2vh;
    border: 1px solid red;
    border-radius: 0.5rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.nav-header1{
    background: lightblue;
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    top: 0;
    width: 100%;
}
.header1-container{
    width: 68vw;
    height: 60px;
    padding: 0 2vh;
    border: 1px solid blue;
    border-radius: 0.5rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

3. 添加滚动监听JavaScript

监听页面滚动事件,根据滚动距离切换两个头部的显示状态:

// 获取两个头部DOM元素
const header1 = document.querySelector('.nav-header1');
const header2 = document.querySelector('.nav-header2');

// 绑定滚动监听事件
window.addEventListener('scroll', function() {
    // 获取当前垂直滚动距离
    const scrollDistance = window.scrollY;
    
    if (scrollDistance > 60) {
        // 滚动超过60px:显示header2,隐藏header1
        header2.style.display = 'flex';
        header1.style.display = 'none';
    } else {
        // 滚动距离≤60px:显示header1,隐藏header2
        header2.style.display = 'none';
        header1.style.display = 'flex';
    }
});

关键说明

  • position: fixed 确保头部始终固定在页面顶部,不会随滚动移出视野
  • 初始隐藏header2,符合"滚动前仅显示header1"的需求
  • 通过window.scrollY获取实时滚动距离,触发显示状态切换

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 23:12:22