如何使用mCustomScroll实现表格表头固定与XY轴滚动
实现固定表头+同步XY滚动的表格(基于mCustomScrollbar)
我来帮你搞定这个固定表头+同步滚动的需求,咱们一步步来调整结构、样式和代码:
步骤1:调整HTML结构
先把表头和内容容器的结构优化下,方便后续同步滚动和固定定位:
<div class="graphData" style="width:86.5%; position: relative; overflow: hidden;"> <!-- 固定表头容器 --> <div class="graphDataTitle"> <table class="thead-table"> <thead></thead> </table> </div> <!-- 可滚动的内容容器 --> <div class="graphDataInner" data-mcs-axis="yx"> <table class="content-table"> <tbody></tbody> </table> </div> </div>
步骤2:添加核心CSS样式
重点是让表头纵向固定,同时和内容表格保持列宽一致,隐藏表头自身的滚动条:
.graphDataTitle { position: sticky; top: 0; z-index: 10; background: #ffffff; /* 用背景色覆盖下方滚动的内容 */ overflow-x: hidden; /* 隐藏表头容器的横向滚动条,靠同步内容滚动实现联动 */ } .graphDataInner { max-height: 400px; /* 设置tbody的最大高度,触发纵向滚动 */ } /* 确保表头和内容表格的列宽完全匹配 */ .thead-table, .content-table { width: 100%; border-collapse: collapse; } .thead-table th, .content-table td { min-width: 100px; /* 根据你的需求调整列宽 */ padding: 8px; border: 1px solid #ddd; }
步骤3:整合JS逻辑(AJAX渲染+滚动初始化+同步联动)
把你的AJAX渲染代码和mCustomScrollbar初始化、滚动同步逻辑结合起来:
// 清空原有表格内容 $('.graphData table thead, .graphData table tbody').empty(); // 渲染表头 var listTitle = $('<tr></tr>').html(` <th>Month</th> <th>orders</th> <th>products</th> <th>sub total</th> <th>shipping</th> <th>coupon</th> <th>bundle</th> <th>credit</th> <th>tax</th> <th>total sale</th> <th>total cost</th> <th>total profit</th> <th>profit [%]</th> `); $('.graphData .thead-table thead').append(listTitle); // 渲染tbody数据 $.each(json.graph_data, function(index){ var item = json.graph_data[index]; var list = $('<tr></tr>').html(` <td>${item[0]}</td> <td>${item[1]}</td> <td>${item[2]}</td> <td>${item[3]} AED</td> <td>${item[4]} AED</td> <td>${item[5]} AED</td> <td>${item[6]} AED</td> <td>${item[7]} AED</td> <td>${item[8]} AED</td> <td class="sale">${item[9]} AED</td> <td class="cost">${item[10]} AED</td> <td class="profit">${item[11]} AED</td> <td class="profit">${item[12]} %</td> `); $('.graphData .content-table tbody').append(list); }); // 初始化mCustomScrollbar $('.graphDataInner').mCustomScrollbar({ axis: "yx", // 启用XY双轴滚动 theme: "minimal", // 可选,自定义滚动条主题 scrollbarPosition: "inside" }); // 监听内容容器滚动,同步表头的横向滚动位置 $('.graphDataInner').on('scroll', function() { const scrollLeft = $(this).scrollLeft(); $('.graphDataTitle').scrollLeft(scrollLeft); });
关键细节说明
- 纵向固定:用
position: sticky实现表头固定在顶部,比绝对定位更灵活,能自适应父容器。 - 列宽匹配:表头和内容表格用相同的宽度规则,避免滚动时出现列错位的情况。
- 滚动同步:通过监听内容容器的
scroll事件,把横向滚动值同步给表头容器,实现X轴滚动联动。 - mCustomScrollbar:替代原生滚动条实现美观的自定义滚动效果,注意要确保你已经正确引入了mCustomScrollbar的JS和CSS文件。
内容的提问来源于stack exchange,提问作者Muhammad Hashir Anwaar
相关产品推荐
相关产品推荐

