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

Angular中水平滚动时激活CSS类的实现方案

水平滚动时激活表格首列阴影类的实现方案

1. 绑定滚动容器的事件监听

给包裹表格的滚动容器添加scroll事件绑定:

<div class="table-container" (scroll)="handleTableScroll($event)">
  <!-- 你的表格结构,首列需带有标识类(如fixed-first-column) -->
</div>

2. 实现滚动逻辑控制类的切换

在组件的TypeScript文件中编写处理方法,根据滚动偏移量判断是否添加/移除目标类:

handleTableScroll(event: Event) {
  const scrollContainer = event.target as HTMLElement;
  const firstColumn = scrollContainer.querySelector('.fixed-first-column');
  if (!firstColumn) return;

  // 当水平滚动偏移量大于0时激活阴影类,否则移除
  scrollContainer.scrollLeft > 0 
    ? firstColumn.classList.add('active-scroll-shadow')
    : firstColumn.classList.remove('active-scroll-shadow');
}

3. 确保阴影样式生效

确认你的CSS类包含正确的阴影效果:

.active-scroll-shadow {
  box-shadow: 3px 0 6px rgba(0, 0, 0, 0.12);
}

可选优化:滚动停止后延迟隐藏阴影

如果希望滚动停止后保留阴影一段时间再隐藏,可添加定时器:

private scrollTimeout: NodeJS.Timeout | null = null;

handleTableScroll(event: Event) {
  const scrollContainer = event.target as HTMLElement;
  const firstColumn = scrollContainer.querySelector('.fixed-first-column');
  if (!firstColumn) return;

  // 清除之前的定时器
  this.scrollTimeout && clearTimeout(this.scrollTimeout);
  // 立即添加阴影类
  firstColumn.classList.add('active-scroll-shadow');

  // 滚动停止1秒后,若回到初始位置则移除阴影
  this.scrollTimeout = setTimeout(() => {
    if (scrollContainer.scrollLeft === 0) {
      firstColumn.classList.remove('active-scroll-shadow');
    }
  }, 1000);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 05:43:16