如果你希望 div 画的表格能够固定表头,可以使用 CSS 中的 position: sticky
属性来实现。具体做法如下:
- 首先,在你的表格 CSS 中为表头添加一个
position: sticky
属性,并指定top
值来控制表头在垂直方向上的固定位置。例如:
.header { position: sticky; top: 0; }
2. 然后,为表格的内容区域设置一个高度和 overflow: auto
属性,用来使内容区域能够滚动。例如:
.contentWarp { height: 200px; overflow: auto; }
需要注意的是,对于 position: sticky
属性的兼容性问题,不同的浏览器可能会有不同的支持程度。目前,主流浏览器(如 Chrome、Firefox、Safari 等)都已经支持了 position: sticky
属性,但是在对于一些旧版本的浏览器,表头可能无法正常固定。如果你需要考虑兼容性的问题,可以使用一些已有的 CSS 库,例如 element-ui、ant-design 等,它们都已经针对表格等组件的固定表头做了充分的兼容性处理
例子如下: 表格自定义组件(固定表头)
<template> <div class="BtmTeble"> <div class="warp"> <h3>{{title || ""}}</h3> <div :class="ts ? 'ts' : ''" class="tabel"> <div class="header"> <div class="cell" :style="{ background: item.bg }" v-for="(item, index) in headerOption" :key="index"> {{ item.label }} </div> </div> <div class="contentWarp"> <div class="content" v-for="(item, index) in contentData" :key="index"> <div class="cell">{{ item.text }}</div> <div class="cell" v-for="(it, i) in item.value" :key="i"> {{ it }} </div> </div> </div> </div> </div> </div> </template> <script> export default { props: ["headerOption", "ts", "tableData",'title'], data() { return { // contentData: [], }; }, computed: { contentData() { return this.tableData } }, methods: {}, }; </script> <style lang="less" scoped> .BtmTeble { background: #fff; .warp { width: calc(100% - 20px); height: auto; border-top: 1px dashed #eee; margin: 10px auto 0; h3 { font-size: 13px; font-family: PingFang SC; font-weight: 400; line-height: 38px; color: #9296a4; opacity: 1; text-align: center; } .tabel { .header { position: sticky; top: 0; .cell { padding: 10px 0; word-break: break-all; } } .contentWarp { height: 200px; overflow: auto; } .header, .content { display: flex; justify-content: space-around; border-left: 1ox solid #fff; .cell { flex: 1; display: flex; justify-content: center; align-items: center; width: 42px; /* height: 65px; */ align-items: center; font-size: 12px; text-align: center; font-family: PingFang SC; font-weight: 400; color: #ffffff; opacity: 1; padding: 4px 2px 0; border: 1px solid #eee; word-break: break-all; } } .content { .cell { display: block; font-size: 13px; font-family: DIN; font-weight: 400; height: 35px; display: flex; align-items: center; justify-content: center; color: #333333; padding: 0; text-align: center; } } .header>.cell, .content>.cell { &:nth-child(1) { font-size: 12px; font-family: PingFang SC; font-weight: 400; color: #9296a4; opacity: 1; } } } .ts { .header>.cell, .content>.cell:first-child { background-color: rgb(241, 251, 248) !important; color: #9296a4 !important; } } } } </style>