4KB原生html实现table下tr的上下次序自由拖动
AI代码,没有翻译和原文链接;经典代码珍藏备用。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Draggable Table Rows with Logs</title>
<style>
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: center;
}
tr.dragging {
background-color: #ffa;
opacity: 0.7;
}
tr.drop-target {
border-top: 3px solid #007bff;
}
#log {
margin-top: 20px;
font-family: monospace;
}
</style>
</head>
<body>
<h2>Draggable Table Rows with Logs</h2>
<table>
<thead>
<tr>
<th>Item</th>
</tr>
</thead>
<tbody id="tableBody">
<tr draggable="true"><td>Row 1</td></tr>
<tr draggable="true"><td>Row 2</td></tr>
<tr draggable="true"><td>Row 3</td></tr>
<tr draggable="true"><td>Row 4</td></tr>
<tr draggable="true"><td>Row 5</td></tr>
</tbody>
</table>
<div id="log">
<h3>Action Log</h3>
</div>
<script>
const tableBody = document.getElementById('tableBody');
let draggedRow = null;
let dropTargetRow = null;
function logAction(fromIndex, toIndex) {
const logDiv = document.getElementById('log');
const logMessage = `${fromIndex + 1} --> ${toIndex + 1}`;
const logEntry = document.createElement('div');
logEntry.textContent = logMessage;
logDiv.appendChild(logEntry);
}
tableBody.addEventListener('dragstart', (event) => {
draggedRow = event.target;
draggedRow.classList.add('dragging');
});
tableBody.addEventListener('dragover', (event) => {
event.preventDefault();
const target = event.target.closest('tr');
if (target && target !== draggedRow) {
dropTargetRow && dropTargetRow.classList.remove('drop-target');
dropTargetRow = target;
dropTargetRow.classList.add('drop-target');
}
});
tableBody.addEventListener('dragleave', (event) => {
const target = event.target.closest('tr');
if (target && target === dropTargetRow) {
dropTargetRow.classList.remove('drop-target');
dropTargetRow = null;
}
});
tableBody.addEventListener('drop', (event) => {
event.preventDefault();
const target = event.target.closest('tr');
if (dropTargetRow && dropTargetRow !== draggedRow) {
const fromIndex = Array.from(tableBody.children).indexOf(draggedRow);
const toIndex = Array.from(tableBody.children).indexOf(dropTargetRow);
// Correct the insert position based on the drag direction
if (fromIndex < toIndex) {
tableBody.insertBefore(draggedRow, dropTargetRow.nextSibling);
logAction(fromIndex, toIndex);
} else {
tableBody.insertBefore(draggedRow, dropTargetRow);
logAction(fromIndex, toIndex);
}
}
resetDragState();
});
tableBody.addEventListener('dragend', resetDragState);
function resetDragState() {
draggedRow && draggedRow.classList.remove('dragging');
dropTargetRow && dropTargetRow.classList.remove('drop-target');
draggedRow = null;
dropTargetRow = null;
}
</script>
</body>
</html>