Vue.js - 解决iView表格固定列高度显示异常问题(自定义滚动条样式引发)
作者:hangge | 2025-01-01 08:34
1,问题描述
(1)我们知道 iView(View UI)的 Table 表格组件支持固定列功能,只需在需要固定的列上添加 fixed 属性即可,该功能在默认情况下一切正常。

(2)由于默认的滚动条样式比较不美观,我们有时会通过全局样式对表格的滚动条样式进行修改,特别是减小了滚动条的宽度(使其变细)。
<style> /* 自定义滚动条整体样式 */ .ivu-table-body::-webkit-scrollbar, .ivu-table-fixed-body::-webkit-scrollbar { width: 8px; /* 垂直滚动条宽度 */ height: 8px; /* 水平滚动条高度 */ } /* 自定义滚动条滑块样式 */ .ivu-table-body::-webkit-scrollbar-thumb, .ivu-table-fixed-body::-webkit-scrollbar-thumb { background-color: #31ab9d; /* 滑块颜色 */ border-radius: 4px; /* 滑块圆角 */ border: 2px solid transparent; /* 边距 */ background-clip: content-box; /* 内边距裁剪 */ } /* 自定义滚动条轨道样式 */ .ivu-table-body::-webkit-scrollbar-track, .ivu-table-fixed-body::-webkit-scrollbar-track { background-color: #f0f0f0; /* 轨道颜色 */ border-radius: 4px; /* 圆角 */ } </style>
(3)这时会发现左侧或者右侧的固定列高度会出现异常,下方出现一段空隙:

2,问题原因
(1)这是因为 iView 在计算固定列的高度时,会先获取滚动条宽度,然后减去滚动条宽度。
(2)而具体算法可以查看 node_modules\iview\src\utils\assist.js 源码,通过自动创建一个隐藏的带滚动条的 div 来获取滚动条宽度。
// For Modal scrollBar hidden let cached; export function getScrollBarSize (fresh) { if (isServer) return 0; if (fresh || cached === undefined) { const inner = document.createElement('div'); inner.style.width = '100%'; inner.style.height = '200px'; const outer = document.createElement('div'); const outerStyle = outer.style; outerStyle.position = 'absolute'; outerStyle.top = 0; outerStyle.left = 0; outerStyle.pointerEvents = 'none'; outerStyle.visibility = 'hidden'; outerStyle.width = '200px'; outerStyle.height = '150px'; outerStyle.overflow = 'hidden'; outer.appendChild(inner); document.body.appendChild(outer); const widthContained = inner.offsetWidth; outer.style.overflow = 'scroll'; let widthScroll = inner.offsetWidth; if (widthContained === widthScroll) { widthScroll = outer.clientWidth; } document.body.removeChild(outer); cached = widthContained - widthScroll; } return cached; }
(3)由于我们只修改了表格的滚动条宽度,而 div 的滚动条宽度没有变化,从而造成计算后的高度不适合。
3,解决办法
(1)既然 iView 是创建一个 div 来获取滚动条宽度,那么我们只要将 div 也设置成同样的宽度样式即可。
/* 自定义滚动条整体样式 */ div::-webkit-scrollbar, .ivu-table-body::-webkit-scrollbar, .ivu-table-fixed-body::-webkit-scrollbar { width: 8px; /* 垂直滚动条宽度 */ height: 8px; /* 水平滚动条高度 */ } /* 自定义滚动条滑块样式 */ .ivu-table-body::-webkit-scrollbar-thumb, .ivu-table-fixed-body::-webkit-scrollbar-thumb { background-color: #31ab9d; /* 滑块颜色 */ border-radius: 4px; /* 滑块圆角 */ border: 2px solid transparent; /* 边距 */ background-clip: content-box; /* 内边距裁剪 */ } /* 自定义滚动条轨道样式 */ .ivu-table-body::-webkit-scrollbar-track, .ivu-table-fixed-body::-webkit-scrollbar-track { background-color: #f0f0f0; /* 轨道颜色 */ border-radius: 4px; /* 圆角 */ }
(2)修改后可以看到固定列区域显示正常了:

全部评论(0)