使用JavaScript写一个可以左右丝滑拖动列宽的表格并且带上样式
时间: 2023-09-08 18:12:08 浏览: 91
你可以使用以下代码实现:
HTML:
```
<table id="myTable">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>30</td>
<td>New York</td>
</tr>
<tr>
<td>Jane</td>
<td>25</td>
<td>Los Angeles</td>
</tr>
<tr>
<td>Bob</td>
<td>40</td>
<td>Chicago</td>
</tr>
</tbody>
</table>
```
CSS:
```
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: left;
}
th {
background-color: #ddd;
}
/* Drag handle styles */
.drag-handle {
position: absolute;
top: 0;
right: -5px;
bottom: 0;
width: 10px;
cursor: col-resize;
z-index: 10;
background-color: #ccc;
}
```
JavaScript:
```
// Get the table element
var table = document.getElementById("myTable");
// Add drag handles to each header cell
var headers = table.getElementsByTagName("th");
for (var i = 0; i < headers.length; i++) {
var handle = document.createElement("div");
handle.className = "drag-handle";
headers[i].appendChild(handle);
}
// Initialize variables
var dragHandle = null;
var startX = 0;
var startWidth = 0;
// Add event listeners for mouse down and up on the drag handles
table.addEventListener("mousedown", function(event) {
if (event.target.className == "drag-handle") {
dragHandle = event.target;
startX = event.pageX;
startWidth = dragHandle.parentNode.offsetWidth;
}
});
table.addEventListener("mouseup", function(event) {
if (dragHandle) {
dragHandle = null;
}
});
// Add event listener for mouse move on the table
table.addEventListener("mousemove", function(event) {
if (dragHandle) {
var width = startWidth + (event.pageX - startX);
dragHandle.parentNode.style.width = width + "px";
}
});
```
这段代码会在表格的每个表头单元格上添加一个拖动句柄,当用户按下并拖动句柄时,表头单元格的宽度会相应地改变。你可以根据需要调整样式。
阅读全文