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

如何用JS/jQuery和CSS基于表格滚动位置动态显隐.price元素

解决方案:基于表格容器滚动控制元素显示/隐藏

核心问题分析

你当前的问题是滚动事件绑定在了全局window上,但实际滚动触发源是.plan-price-container容器,所以需要把滚动监听对象切换到容器本身,再结合表头粘性触发的滚动位置来控制.price元素的显隐。

修改步骤

1. 调整CSS(确保表头粘性生效)

完善表头的粘性样式,避免下方内容穿透:

.plan-price-container {
  height: 600px;
  overflow-y: auto;
  /* 可选:添加上内边距,避免表头贴容器顶部 */
  padding-top: 8px;
}

/* 表头粘性核心样式 */
thead th {
  position: sticky;
  top: 0;
  background-color: #fff; /* 必须设置背景色,防止下方内容穿透 */
  z-index: 1; /* 确保表头在内容上方 */
}

/* 价格区域的隐藏类 */
.price.hidden {
  display: none;
}

2. 修改JavaScript(监听容器滚动并判断位置)

把滚动事件绑定到.plan-price-container,并根据滚动位置精准控制价格区域显隐:

// 获取目标DOM元素
const scrollContainer = document.querySelector('.plan-price-container');
const priceElement = document.querySelector('.price');
const tableHeader = document.querySelector('thead');

// 初始化时获取表头相对于容器的初始顶部距离(精准判断表头开始固定的时机)
const headerInitialTop = tableHeader.offsetTop;

// 监听容器滚动事件
scrollContainer.addEventListener('scroll', function() {
  // 当滚动距离超过表头初始位置时隐藏价格区域,否则恢复显示
  if (this.scrollTop >= headerInitialTop) {
    priceElement.classList.add('hidden');
  } else {
    priceElement.classList.remove('hidden');
  }
});

3. 可选优化:防抖处理

如果滚动时函数触发频率过高,可添加防抖函数减少性能消耗:

// 防抖工具函数
function debounce(func, delay = 100) {
  let timer;
  return function() {
    clearTimeout(timer);
    timer = setTimeout(() => func.apply(this, arguments), delay);
  };
}

// 用防抖包裹滚动处理逻辑
scrollContainer.addEventListener('scroll', debounce(function() {
  if (this.scrollTop >= headerInitialTop) {
    priceElement.classList.add('hidden');
  } else {
    priceElement.classList.remove('hidden');
  }
}));

原理说明

  • 表头通过position: sticky + top: 0实现粘性固定,当容器滚动至表头到达容器顶部时,表头会固定在该位置。
  • 监听容器的scroll事件,通过滚动距离与表头初始位置的对比,精准触发价格区域的显隐逻辑。
  • 防抖函数可降低滚动时的函数调用频率,避免不必要的性能损耗。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 17:54:52