vue3 element el-table表头冻结,表头吸顶directives方法
1、在文件夹中创建directives文件
/**
* 思路:通过简体 el-table的 thead和tbody父级别区域,进行设置对于的fixed
*/
function getElParentBySelector(el, queryClassSelector) {
if (!el) {
return el
}
if ([...el.classList].includes(queryClassSelector)) {
return el
}
return getElParentBySelector(el.parentNode, queryClassSelector)
}
function getTableShowWidth(thead) {
const tableBox = getElParentBySelector(thead, 'el-table')
return tableBox.getBoundingClientRect().width
}
function createTableSticky(el, binding) {
// 获取表格(element)
console.log(el,99937)
let thead = el.querySelector('.el-table__header')
thead = getElParentBySelector(thead, 'el-table__header-wrapper')
const tbody = el.querySelector('.el-table__body')
//获取thead 的显示宽度
const headerShowWidth = getTableShowWidth(thead)
// 获取滚动元素
const scrollParent = document.querySelector(binding.value.parent||'body')
console.log(scrollParent,binding.value.disabled,88882)
if (!scrollParent || binding.value.disabled === true) {
return
}
scrollParent.addEventListener('scroll', function () {
const stickyTop= binding.value.top||0;
const theadHeight = thead.clientHeight
// 获取thead距离顶部的距离
const theadTop = thead.getBoundingClientRect().top
console.log(theadTop,theadHeight,"theadToptheadTop")
if (theadTop <= stickyTop) {
tbody.style.paddingTop = theadHeight + 'px'
thead.style.position = 'fixed'
thead.style.zIndex = '2021'
thead.style.top = stickyTop + 'px'
thead.style.borderTop = '1px solid #EBEBEB'
//thead.style.width = tbody.offsetWidth + 'px' //
//使用最佳显示宽度显示内容,防止有横向滚动条时,固定列显示超出
thead.style.width =
(tbody.offsetWidth < headerShowWidth ? tbody.offsetWidth : headerShowWidth) + 'px'
//获取父级别的宽度,设置列头行只能是负极宽度
}
// 判断是否需要回归原来位置
const originally = tbody.getBoundingClientRect().top
// 判断底部距离是否超过表头
const goBeyond = tbody.getBoundingClientRect().bottom
if (originally > stickyTop || 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' //固定表头有bug的话改成 auto
thead.style.borderTop = 'none'
}
})
}
var clearTimeId = 0;
const createSticky = {
mounted(el, binding) {
//TIP 延时设置,确保表格进行渲染成功!
// el.addEventListener("scroll", createTableSticky(el, binding));
clearTimeId = setTimeout(() => {
createTableSticky(el, binding)
clearTimeout(clearTimeId)
}, 1000)
},
unmounted(el, binding) {
clearTimeId && clearTimeout(clearTimeId)
}
}
export default createSticky
2、在main中引用全局
const app = createApp(App);
import createSticky from './directives/sticky'
app.directive('sticky',createSticky)
app.mount("#app");
3、使用:
v-sticky="{ top: 185, parent: '.page_main' }"
注意:table不要加高度,数据少于高度列时会在数据最后一列那消失
page_main是指有滚轮的父级页面
参考:
https://blog.csdn.net/qq_28254093/article/details/134642885