如何用JS函数实现表格指定列数的滚动冻结效果?
可以通过JS函数动态生成冻结列样式,不用手动写nth-child规则
当然可以!你完全可以写一个JS函数,传入要冻结的列数,动态循环生成对应的CSS规则,还能自动计算每列的left偏移量(不用手动写30px、138px这种固定值)。
下面是适配你现有样式的实现方案:
// 生成冻结列样式的函数 function generateStickyColumnStyles(freezeCount, firstColStyles, otherColStyles) { let styles = ''; let currentLeft = 0; for (let i = 1; i <= freezeCount; i++) { // 构造当前列的选择器 const thSelector = `table:first-of-type thead tr th:nth-child(${i})`; const tdSelector = `table:first-of-type tbody tr td:nth-child(${i})`; // 区分第一列和其他列的样式配置 const isFirstCol = i === 1; const thStyle = isFirstCol ? firstColStyles.th : otherColStyles.th; const tdStyle = isFirstCol ? firstColStyles.td : otherColStyles.td; // 拼接当前列的完整样式 styles += ` ${thSelector}{ position: sticky; position: -webkit-sticky; ${thStyle} left: ${currentLeft}px; z-index: 3; } ${tdSelector}{ position: sticky; position: -webkit-sticky; ${tdStyle} left: ${currentLeft}px; z-index: 1; } `; // 更新下一列的left偏移值 if (i < freezeCount) { // 这里可以换成动态获取列宽:document.querySelector(thSelector).offsetWidth // 示例中沿用你原来的列宽数值:第一列30px,后续列108px(138-30) currentLeft += isFirstCol ? 30 : 108; } } return styles; } // 调用函数,生成冻结3列的样式 const stickyStyles = generateStickyColumnStyles(3, { th: 'background-color:white; color:crimson;', td: 'background: crimson; color:black;' }, { th: 'color: black;', td: 'background: black;' }); // 将样式插入页面 const styleSheet = document.createElement("style"); styleSheet.innerText = stickyStyles; document.head.appendChild(styleSheet);
关键优化点:
- 灵活配置:支持自定义冻结列数,还能分别设置第一列和其他列的样式
- 自动计算偏移:不用手动计算每列的
left值,如果列宽不固定,可把偏移计算逻辑换成动态获取列宽:// 替换原来的currentLeft累加逻辑 const colWidth = document.querySelector(thSelector).offsetWidth; currentLeft += colWidth; - 易扩展:后续要冻结更多列,只需要修改
generateStickyColumnStyles的第一个参数即可,无需手动编写重复的CSS规则
内容的提问来源于stack exchange,提问作者Conrado
相关产品推荐
相关产品推荐

