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

计算滚动位置:实现向下滚动隐藏、回滚即时显示元素

实现滚动方向触发的显示/隐藏效果

你需要的是根据滚动方向即时触发目标div的显示/隐藏:向下滚动时消失,向上滚动时立即显示。原代码仅固定判断滚动位置小于5时显示,无法满足需求,以下是修改后的实现方案:

修改后的代码

JavaScript

// 记录上一次的滚动位置
let lastScrollTop = 0;
const searchBar = document.getElementById('search-bar-scroll');

window.addEventListener('scroll', function() {
  const currentScrollTop = window.scrollY;
  
  // 判断滚动方向
  if (currentScrollTop > lastScrollTop) {
    // 向下滚动:隐藏搜索栏
    searchBar.classList.remove('scrolled');
  } else {
    // 向上滚动:显示搜索栏
    searchBar.classList.add('scrolled');
  }
  
  // 更新上一次滚动位置
  lastScrollTop = currentScrollTop;
});

CSS

* {
  margin: 0;
  padding: 0;
}

img,
fieldset {
  border: none;
}

body *,
*:after,
*:before {
  box-sizing: border-box;
}

html,
body {
  height: 250vh;
}

.main-wrapper {
  max-width: 1400px;
  margin-left: auto;
  margin-right: auto;
}

.search-bar-scroll {
  background: #1e5da5;
  position: fixed;
  height: auto;
  width: 100%;
  left: 0;
  top: 0;
  opacity: 0;
  transition: opacity 0.3s ease; /* 统一过渡效果 */
}

.scrolled {
  opacity: 1;
}

HTML

<div class="search-bar-scroll" id="search-bar-scroll">
  <fieldset class="home-header-search">
    <div action="#" id="scroll-input-container">
      <p>Hello World</p>
    </div>
  </fieldset>
</div>

逻辑说明

  • 用lastScrollTop变量记录上一次的滚动位置,每次滚动时和当前scrollY对比
  • 向下滚动时(当前位置大于上次位置),移除scrolled类,通过opacity过渡隐藏div
  • 向上滚动时(当前位置小于上次位置),添加scrolled类,即时显示div
  • 统一CSS过渡效果,避免多个transition冲突,让动画更流畅

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 04:05:22