小分辨率下滚动时隐藏被粘性表头覆盖的表头
实现粘性表头覆盖时自动隐藏后续表头
方案思路
通过监听表格容器的横向滚动事件,结合第一个粘性表头的宽度判断滚动位置,当后续表头与粘性表头重叠时,为其添加隐藏样式;滚动回原位置时恢复显示,确保视觉上只有粘性表头保留。
修改后的代码
CSS 部分
.horizontal-scroll-table > .row::-webkit-scrollbar { display: none; } table thead th { background-color: #111A40; color: white; padding: 16px 24px; transition: opacity 0.2s ease; /* 过渡效果让显示/隐藏更自然 */ } table thead th:last-child { border-radius: 0 50px 50px 0; } table thead th:first-child { border-radius: 50px 0 0 50px; position: sticky !important; left: 0; z-index: 999; } /* 隐藏类:透明化并禁用交互 */ table thead th.hidden { opacity: 0; pointer-events: none; } @media (max-width: 991px) { .horizontal-scroll-table > .row { overflow-x: scroll; white-space: nowrap; overflow-y: hidden; } .horizontal-scroll-table > .row > .col-md-12 { display: inline-block; float: none; } }
HTML 部分
<div class="horizontal-scroll-table"> <div class="row" style="text-align: -webkit-center;"> <table> <thead style="background-color: #111A40;"> <tr> <th>Sticky header</th> <th>header</th> <th>header</th> <th>header</th> </tr> </thead> <!-- 添加测试用tbody内容 --> <tbody> <tr> <td>列1内容</td> <td>列2内容</td> <td>列3内容</td> <td>列4内容</td> </tr> <tr> <td>列1内容</td> <td>列2内容</td> <td>列3内容</td> <td>列4内容</td> </tr> </tbody> </table> </div> </div>
JavaScript 部分
const scrollContainer = document.querySelector('.horizontal-scroll-table .row'); const stickyTh = document.querySelector('table thead th:first-child'); const otherThs = document.querySelectorAll('table thead th:not(:first-child)'); // 获取粘性表头的实际宽度 const stickyThWidth = stickyTh.offsetWidth; // 监听滚动事件处理表头显示/隐藏 scrollContainer.addEventListener('scroll', () => { const scrollLeft = scrollContainer.scrollLeft; otherThs.forEach(th => { scrollLeft >= stickyThWidth ? th.classList.add('hidden') : th.classList.remove('hidden'); }); }); // 页面加载时初始化检查,避免初始滚动状态下显示异常 window.addEventListener('load', () => { const scrollLeft = scrollContainer.scrollLeft; otherThs.forEach(th => { if (scrollLeft >= stickyThWidth) th.classList.add('hidden'); }); });
方案说明
- 借助滚动事件实时获取容器滚动位置,对比粘性表头宽度判断重叠状态。
- 通过
hidden类控制表头透明度,搭配过渡动画提升视觉流畅度。 pointer-events: none避免隐藏的表头干扰页面交互。
内容的提问来源于stack exchange,提问作者Robert
相关产品推荐
相关产品推荐

