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

JavaScript实现div内滚动时数组项到达顶部显示隐藏元素求助

问题修正与解决方案

原有代码核心问题

  • 事件绑定对象错误:scroll事件发生在外层可滚动的.container容器上,你给内部子元素.show-more绑定滚动事件,事件永远不会触发。
  • 滚动距离取值错误:document.body.scrollTop是整个页面的滚动距离,你需要获取的是.container容器自身的滚动距离。
  • 位置判断逻辑错误:固定100px的断点无法适配所有子元素的位置,需要动态判断每个.show-more元素相对于容器顶部的位置。
  • 类名操作逻辑错误:使用toggle会导致元素在滚动时反复显示隐藏,应该是符合显示条件时加类,不符合时移除类。
  • 语法错误:JS代码末尾缺少闭合的括号与大括号,代码本身无法正常运行。

修正后完整代码

JS代码

// 获取滚动容器和所有条目
const container = document.querySelector('.container');
const itemList = Array.from(document.querySelectorAll('.container > div'));

// 给滚动容器绑定scroll事件
container.addEventListener('scroll', () => {
  // 获取容器顶部相对于视口的位置
  const containerTop = container.getBoundingClientRect().top;
  // 先隐藏所有content元素
  document.querySelectorAll('.content').forEach(el => el.classList.remove('showdiv'));

  // 遍历所有条目判断位置
  itemList.forEach(item => {
    const showMoreEl = item.querySelector('.show-more');
    // 计算当前show-more元素距离容器顶部的距离
    const offsetTop = showMoreEl.getBoundingClientRect().top - containerTop;
    // 位置在0-30px范围内判定为到达容器顶部,可自行调整阈值
    if (offsetTop >= 0 && offsetTop < 30) {
      item.querySelector('.content').classList.add('showdiv');
    }
  })
})

CSS代码

仅做了可选优化,原有逻辑可正常使用:

.container {
  width: 200px;
  overflow: auto;
  height: 300px !important;
  background-color: salmon;
  /* 可选:如果需要content相对于容器定位可开启下面这行 */
  /* position: relative; */
}
.content {
  display: none;
  height: 50px;
  background-color: green;
  position: absolute;
  right: 100px;
  top: 0; /* 可选:固定content显示在容器右侧顶部 */
}
.show-more {
    height: 100px;
    border-bottom: 1px solid blue;
}
.showdiv {
  display: block !important;
}

HTML代码

和你原有代码完全一致,无需修改。

实现逻辑说明

每次容器滚动时,先清空所有content元素的显示状态,再遍历所有条目,计算每个.show-more元素距离容器顶部的偏移量,偏移量在阈值范围内的条目就显示对应的content元素,可自行调整阈值数值适配你的交互需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 04:39:03