仅限无固定列情况下使用
// el-table表头吸顶效果
Vue.directive('sticky', {
// 当被绑定的元素插入到 DOM 中时……
inserted(el, binding) {
// 获取表格(element)
let thead = el.children[1];
let tbody = el.children[2];
// 获取滚动元素
const scrollParent = document.querySelector(binding.value.parent);
scrollParent.addEventListener('scroll', function() {
const theadHeight = thead.clientHeight
// 获取thead距离顶部的距离
let theadTop = thead.getBoundingClientRect().top;
if (theadTop <= binding.value.top) {
tbody.style.paddingTop = theadHeight + 'px'
thead.style.position = 'fixed';
thead.style.zIndex = '2021';
thead.style.top = binding.value.top + 'px';
thead.style.width = tbody.offsetWidth + 'px';
thead.style.borderTop = '1px solid #EBEBEB';
}
// 判断是否需要回归原来位置
let originally = tbody.getBoundingClientRect().top;
// 判断底部距离是否超过表头
let goBeyond = tbody.getBoundingClientRect().bottom;
if (originally > binding.value.top || goBeyond <= thead.offsetHeight) {
tbody.style.paddingTop = '0'
thead.style.position = 'relative';
thead.style.zIndex = '0';
thead.style.top = 0 + 'px';
thead.style.width = tbody.offsetWidth + 'px';
thead.style.borderTop = 'none';
}
});
}
});
<el-table v-sticky="{top: 100, parent: '.page-wrap'}">
// top是表头吸顶后和浏览器顶部的距离,parent是滚动元素的id或class
网友评论