原生js實現表頭拖拽效果
使用原生js實現表頭拖拽效果
方法獨立jq,使用面向對象方法,可以改造成ts嵌入vue項目中或者拓展el-table表頭固定,不影響el-table排序的拖拽問題
代碼如下,有不足之處的請幫忙指出
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>原生實現table拖拽滾動</title>
<style>
.scrollTableBox {
width: 100%;
max-width: 300px;
margin: auto;
overflow-x: scroll;
}
.scrollTableBox table {
width: 100%;
border-collapse: collapse;
}
.scrollTableBox.dragActive table{
user-select: none;
}
.scrollTableBox th,
.scrollTableBox td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
.scrollTableBox thead th {
background-color: #f2f2f2;
white-space: nowrap;
}
</style>
</head>
<body>
<div class="scrollTableBox">
<table class="scrollTable" id="scrollable" border>
<thead>
<tr>
<th>序號</th>
<th>產品</th>
<th>標題</th>
<th>型號</th>
<th>內容</th>
<th>備注</th>
<th>售前價格</th>
<th>活動價格</th>
<th>促銷抵扣</th>
<th>積分</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
<td>10</td>
</tr>
<tr>
<td>21</td>
<td>22</td>
<td>23</td>
<td>24</td>
<td>25</td>
<td>26</td>
<td>27</td>
<td>28</td>
<td>29</td>
<td>210</td>
</tr>
<tr>
<td>321</td>
<td>322</td>
<td>323</td>
<td>324</td>
<td>325</td>
<td>326</td>
<td>327</td>
<td>328</td>
<td>329</td>
<td>3210</td>
</tr>
</tbody>
</table>
</div>
<script>
class HeaderDraggable {
constructor(scrollContainer) {
this.isDragging = false;
this.startX = 0;
this.scrollLeft = 0;
this.scrollContainer = scrollContainer;
this.startDrag = this.startDrag.bind(this);
this.drag = this.drag.bind(this);
this.endDrag = this.endDrag.bind(this);
if (this.scrollContainer) {
let thead = this.scrollContainer.querySelector('thead');
thead.addEventListener('mousedown', this.startDrag);
}
}
startDrag(e) {
this.isDragging = true;
this.startX = e.pageX;
this.scrollLeft = this.scrollContainer ? this.scrollContainer.scrollLeft : 0;
this.scrollContainer.classList.add('dragActive');
this.scrollContainer.style.cursor = 'grabbing';
document.addEventListener('mousemove', this.drag);
document.addEventListener('mouseup', this.endDrag);
}
drag(e) {
if (!this.isDragging) return;
const scrollX = this.startX - e.pageX;
if (this.scrollContainer) {
this.scrollContainer.scrollLeft = this.scrollLeft + scrollX;
}
}
endDrag() {
this.isDragging = false;
this.scrollContainer.classList.remove('dragActive');
this.scrollContainer.style.cursor = 'auto';
document.removeEventListener('mousemove', this.drag);
document.removeEventListener('mouseup', this.endDrag);
}
cleanup() {
if (this.scrollContainer) {
this.scrollContainer.removeEventListener('mousedown', this.startDrag);
}
document.removeEventListener('mousemove', this.drag);
document.removeEventListener('mouseup', this.endDrag);
}
}
const initTableScroll = () => {
const table = document.querySelector('.scrollTableBox');
if (!table) return;
const headerDraggable = new HeaderDraggable(table);
}
initTableScroll()
</script>
</body>
</html>

浙公網安備 33010602011771號