废话不多说,间接上思路
通过 sticky 实现 element-ui 表头吸顶,具体步骤如下
- 新建一个 sticky 容器
- 将 element-ui 的表头挪动至这个容器中
- 解决左侧固定列
贴代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
.first-title {
height: 300px;
background: #f00;
}
</style>
<body>
<div class="first-title">
this is title
</div>
<div id="app">
<el-table
v-table-sticky="{top:'0px', zIndex: 101}"
:data="tableData"
style="width: 100%">
<el-table-column
prop="date"
label="日期"
width="180">
</el-table-column>
<el-table-column
prop="name"
label="姓名"
width="180">
</el-table-column>
<el-table-column
prop="address"
label="地址">
</el-table-column>
</el-table>
</div>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- 引入款式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
Vue.directive('table-sticky', {
// 当被绑定的元素插入到 DOM 中时……
inserted (el, binding, vnode) {
// 获取以后 vueComponent 的 ID。作为寄存各种监听事件的 key
const uid = binding.value.uid
let panel = document.createElement("div");
panel.className = 'el-table el-table--fit el-table--enable-row-transition el-table--small';
panel.style=`position: sticky;top: ${binding.value.top}; z-index: ${binding.value.zIndex};`;
console.log('uid_is',[el,uid])
$(panel).insertBefore(el)
let func = function () {let elFixed = $(el).children('.el-table__fixed');
if ($(el).children('.el-table__header-wrapper')[0] !== undefined) {panel.append($(el).children('.el-table__header-wrapper')[0])
}
elFixed.children('.el-table__fixed-header-wrapper').width(elFixed.width()).css('overflow', 'hidden')
elFixed.children('.el-table__fixed-body-wrapper').css('top',0)
if (elFixed.children('.el-table__fixed-header-wrapper')[0] !== undefined) {panel.append(elFixed.children('.el-table__fixed-header-wrapper')[0])
}
if (binding.value.isFooter === true) {if ($(el).children('.el-table__footer-wrapper')[0] !== undefined) {panel.append($(el).children('.el-table__footer-wrapper')[0])
}
if (elFixed.children('.el-table__fixed-footer-wrapper')[0] !== undefined) {panel.append(elFixed.children('.el-table__fixed-footer-wrapper')[0])
}
}
}
for (let i = 100; i <= 1500; i=i+100) {setTimeout(function() {func()
},i);
}
// 获取以后滚动的容器是什么。如果是 document 滚动。则可默认不传入 parent 参数
},
// component 更新后。从新计算表头宽度
componentUpdated (el, binding, vnode) {let elFixed = $(el).children('.el-table__fixed');
elFixed.children('.el-table__fixed-body-wrapper').css('top',0)
},
// 节点勾销绑定时 移除各项监听事件。unbind (el, binding, vnode) {}})
var app= new Vue({
el:"#app", // 绑定的元素
data:{tableData: []
},
created() {for (let i = 0; i < 1000; i++) {
this.tableData.push({
date: '2016-05-03',
name: '王小虎',
address: '上海市普陀区金沙江路 1516 弄'
})
}
}
});
</script>
</html>