```html
body {
fontfamily: Arial, sansserif;
padding: 20px;
}
h1 {
color: 333;
textalign: center;
}
.container {
display: flex;
justifycontent: spacearound;
alignitems: flexstart;
height: 400px;
}
.sidebar {
width: 200px;
backgroundcolor: f4f4f4;
padding: 10px;
borderradius: 5px;
boxshadow: 2px 2px 6px ddd;
}
.workspace {
flex: 1;
backgroundcolor: fff;
borderradius: 5px;
boxshadow: 2px 2px 6px ddd;
padding: 20px;
}
.draggable {
margin: 5px 0;
padding: 10px;
backgroundcolor: 3498db;
color: fff;
cursor: move;
borderradius: 5px;
textalign: center;
userselect: none;
}
在线拖拽编程
const draggables = document.querySelectorAll('.draggable');
const workspace = document.getElementById('workspace');
draggables.forEach(draggable => {
draggable.addEventListener('dragstart', () => {
draggable.classList.add('dragging');
});
draggable.addEventListener('dragend', () => {
draggable.classList.remove('dragging');
});
});
workspace.addEventListener('dragover', e => {
e.preventDefault();
const afterElement = getDragAfterElement(workspace, e.clientY);
const draggable = document.querySelector('.dragging');
if (afterElement == null) {
workspace.appendChild(draggable);
} else {
workspace.insertBefore(draggable, afterElement);
}
});
function getDragAfterElement(container, y) {
const draggableElements = [...container.querySelectorAll('.draggable:not(.dragging)')];
return draggableElements.reduce((closest, child) => {
const box = child.getBoundingClientRect();
const offset = y box.top box.height / 2;
if (offset < 0 && offset > closest.offset) {
return { offset: offset, element: child };
} else {
return closest;
}
}, { offset: Number.NEGATIVE_INFINITY }).element;
}