js 实现表头固定,列宽可拖动改变宽度大小
时间: 2023-06-18 22:07:34 浏览: 161
一个可拖拽列宽表格实例演示
实现表头固定和列宽可拖动改变宽度大小的方案可以使用 CSS 和 JavaScript 来实现。下面是一个简单的示例代码:
HTML:
```html
<div class="table-wrapper">
<table>
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
<td>Row 1, Column 3</td>
<td>Row 1, Column 4</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
<td>Row 2, Column 3</td>
<td>Row 2, Column 4</td>
</tr>
<tr>
<td>Row 3, Column 1</td>
<td>Row 3, Column 2</td>
<td>Row 3, Column 3</td>
<td>Row 3, Column 4</td>
</tr>
<tr>
<td>Row 4, Column 1</td>
<td>Row 4, Column 2</td>
<td>Row 4, Column 3</td>
<td>Row 4, Column 4</td>
</tr>
</tbody>
</table>
</div>
```
CSS:
```css
.table-wrapper {
overflow-x: auto;
max-width: 100%;
}
table {
border-collapse: collapse;
width: 100%;
}
th, td {
padding: 8px;
text-align: left;
border: 1px solid #ddd;
}
th {
position: sticky;
top: 0;
background-color: #f2f2f2;
}
td {
font-size: 14px;
}
.resize-handle {
position: absolute;
top: 0;
right: 0;
bottom: 0;
width: 10px;
cursor: col-resize;
z-index: 1;
background-color: #fff;
border-left: 1px solid #ddd;
}
```
JavaScript:
```javascript
const table = document.querySelector('table');
const cols = table.querySelectorAll('th');
let isResizing = false;
let currentCol = null;
let initialX = null;
let currentWidth = null;
cols.forEach(col => {
const resizeHandle = document.createElement('div');
resizeHandle.classList.add('resize-handle');
col.appendChild(resizeHandle);
resizeHandle.addEventListener('mousedown', function(event) {
currentCol = event.target.parentElement;
initialX = event.clientX;
currentWidth = parseInt(getComputedStyle(currentCol).width, 10);
isResizing = true;
});
});
document.addEventListener('mousemove', function(event) {
if (isResizing) {
const width = currentWidth + event.clientX - initialX;
currentCol.style.width = `${width}px`;
}
});
document.addEventListener('mouseup', function(event) {
isResizing = false;
currentCol = null;
initialX = null;
currentWidth = null;
});
```
这段代码使用了 CSS 的 sticky 定位和 JavaScript 的 mousemove 和 mouseup 事件,以实现表头固定和列宽可拖动改变宽度大小的效果。可以根据具体需求进行调整。
阅读全文