You need to enable JavaScript to run this app. 如何使用JavaScript在屏幕宽度小于767px时滚动后隐藏固定div
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript在屏幕宽度小于767px时滚动后隐藏固定div

实现方案

步骤1:调整CSS样式

首先新增滚动隐藏专用类,用过渡动画保证交互丝滑,同时给固定元素添加默认过渡属性:

/* 给两个固定元素添加默认过渡 */
#magic, #music {
  transition: all 0.3s ease !important;
}

/* 滚动隐藏类,滚动触发时添加到元素上 */
.scroll-hidden {
  opacity: 0 !important;
  transform: translateY(-80px) !important;
  pointer-events: none !important;
}

注意:如果你原有媒体查询中#music的top: -550px是不需要的默认隐藏配置,可以删除该属性,否则该元素默认就不在移动端可视区,滚动隐藏效果无法观测。

步骤2:添加JS滚动监听逻辑

在页面</body>闭合标签前插入以下代码,仅在屏幕宽度小于767px时触发滚动显隐逻辑:

// 防抖函数,减少滚动事件触发频率,优化性能
function debounce(func, delay) {
  let timer = null;
  return function() {
    clearTimeout(timer);
    timer = setTimeout(() => func.apply(this, arguments), delay);
  }
}

function toggleFixedElVisibility() {
  // 屏幕宽度大于767px时不执行逻辑
  if (window.innerWidth >= 767) return;
  // 滚动触发阈值,单位px,可自行调整
  const scrollTrigger = 30;
  // 选择需要控制显隐的固定元素,可按需修改选择器
  const targetEls = document.querySelectorAll('#magic, #music');

  if (window.scrollY > scrollTrigger) {
    targetEls.forEach(el => el.classList.add('scroll-hidden'));
  } else {
    targetEls.forEach(el => el.classList.remove('scroll-hidden'));
  }
}

// 绑定事件
window.addEventListener('scroll', debounce(toggleFixedElVisibility, 100));
window.addEventListener('load', toggleFixedElVisibility);
window.addEventListener('resize', debounce(toggleFixedElVisibility, 100));

自定义调整说明

  • 仅需隐藏单个元素时,修改document.querySelectorAll内的选择器即可,比如改为#magic就只控制Magic按钮的显隐
  • 调整scrollTrigger的数值可以修改滚动触发隐藏的距离,数值越大需要滚动更远才会隐藏元素
  • 不需要过渡动画时,可以把.scroll-hidden的属性改为display: none !important即可直接隐藏元素

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 14:45:03