js拖拽这个组件页面进行伸缩,里面是表格,同步进行伸缩
时间: 2024-05-05 08:15:49 浏览: 120
flex objecthandles一个很不错的拖拽伸缩控件
5星 · 资源好评率100%
以下是一个简单的示例:
HTML:
```html
<div id="container">
<div id="drag-handle"></div>
<table>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
<td>Row 1, Column 3</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
<td>Row 2, Column 3</td>
</tr>
<tr>
<td>Row 3, Column 1</td>
<td>Row 3, Column 2</td>
<td>Row 3, Column 3</td>
</tr>
</table>
</div>
```
CSS:
```css
#container {
position: relative;
width: 100%;
height: 200px;
overflow: hidden;
}
#drag-handle {
position: absolute;
top: 0;
right: 0;
width: 10px;
height: 100%;
background-color: gray;
cursor: ew-resize;
}
table {
width: 100%;
height: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding: 5px;
}
```
JavaScript:
```javascript
var dragHandle = document.getElementById('drag-handle');
var container = document.getElementById('container');
var table = container.getElementsByTagName('table')[0];
var dragging = false;
var startX = 0;
var startWidth = 0;
dragHandle.addEventListener('mousedown', function(event) {
event.preventDefault();
startX = event.clientX;
startWidth = container.offsetWidth;
dragging = true;
});
document.addEventListener('mousemove', function(event) {
if (dragging) {
var width = startWidth + (event.clientX - startX);
container.style.width = width + 'px';
table.style.width = width + 'px';
}
});
document.addEventListener('mouseup', function(event) {
if (dragging) {
dragging = false;
}
});
```
这个示例中,我们在容器(`#container`)中添加了一个拖拽手柄(`#drag-handle`),用于控制容器的宽度。当用户按下拖拽手柄时,我们记录下起始的鼠标位置和容器宽度,并将`dragging`标志设置为`true`。在鼠标移动期间,如果`dragging`为`true`,则根据鼠标位置更新容器和表格的宽度。当用户松开鼠标时,我们将`dragging`标志设置为`false`。
阅读全文