自己分装table 左侧固定
时间: 2023-10-08 12:09:41 浏览: 74
要实现左侧固定的表格,可以使用CSS中的position和overflow属性。具体步骤如下:
1. HTML结构:
```html
<div class="table-wrap">
<table class="table">
<thead>
<tr>
<th>固定列1</th>
<th>列2</th>
<th>列3</th>
...
</tr>
</thead>
<tbody>
<tr>
<td>固定列1</td>
<td>内容2</td>
<td>内容3</td>
...
</tr>
...
</tbody>
</table>
<div class="fixed-column"></div>
</div>
```
2. CSS样式:
```css
.table-wrap {
position: relative;
overflow: hidden;
}
.table {
width: 100%;
border-collapse: collapse;
}
.table th,
.table td {
border: 1px solid #ccc;
padding: 10px;
}
.fixed-column {
position: absolute;
top: 0;
left: 0;
width: auto;
overflow-y: auto;
overflow-x: hidden;
border-right: 1px solid #ccc;
background-color: #fff;
}
.fixed-column td,
.fixed-column th {
position: relative;
z-index: 1;
border-top: none;
border-bottom: none;
border-left: none;
}
```
3. JavaScript代码:
```javascript
var tableWrap = document.querySelector('.table-wrap');
var fixedColumn = document.querySelector('.fixed-column');
tableWrap.addEventListener('scroll', function() {
fixedColumn.style.top = tableWrap.scrollTop + 'px';
});
```
这里的关键是使用position: absolute将固定列的div脱离文档流,然后使用overflow-y: auto和overflow-x: hidden实现纵向滚动。JavaScript代码则是监听父元素的scroll事件,将固定列的top值设为父元素的scrollTop值。