class DraggableList {
constructor(containerId) {
this.container = document.getElementById(containerId);
this.items = ['项目1', '项目2', '项目3', '项目4'];
this.init();
}
init() {
this.render();
this.bindDragEvents();
}
render() {
this.container.innerHTML = `
${this.items.map((item, index) => `
-
${item}
`).join('')}
`;
}
bindDragEvents() {
const items = this.container.querySelectorAll('.draggable-item');
items.forEach(item => {
item.addEventListener('dragstart', this.handleDragStart.bind(this));
item.addEventListener('dragover', this.handleDragOver.bind(this));
item.addEventListener('drop', this.handleDrop.bind(this));
item.addEventListener('dragend', this.handleDragEnd.bind(this));
});
}
handleDragStart(e) {
e.dataTransfer.setData('text/plain', e.target.dataset.index);
e.target.classList.add('dragging');
}
handleDragOver(e) {
e.preventDefault();
}
handleDrop(e) {
e.preventDefault();
const draggedIndex = parseInt(e.dataTransfer.getData('text/plain'));
const targetIndex = parseInt(e.target.dataset.index);
if (draggedIndex !== targetIndex) {
const draggedItem = this.items[draggedIndex];
this.items.splice(draggedIndex, 1);
this.items.splice(targetIndex, 0, draggedItem);
this.render();
this.bindDragEvents();
}
}
handleDragEnd(e) {
e.target.classList.remove('dragging');
}
}