js 左侧多个拖拽内容,拖拽其中一个dom到右侧,右侧dom判断拖拽到dom内,未释放前可进行排序,右侧dom可拖拽排序,请用完整代码实现
时间: 2024-01-06 22:04:26 浏览: 167
好的,以下是一个完整的实现示例:
HTML:
```html
<div class="left">
<div class="item" draggable="true">拖拽内容1</div>
<div class="item" draggable="true">拖拽内容2</div>
<div class="item" draggable="true">拖拽内容3</div>
</div>
<div class="right">
<div class="dropzone">拖拽到这里</div>
</div>
```
CSS:
```css
.left {
float: left;
width: 50%;
height: 200px;
border: 1px solid #ccc;
padding: 10px;
box-sizing: border-box;
}
.right {
float: left;
width: 50%;
height: 200px;
border: 1px solid #ccc;
padding: 10px;
box-sizing: border-box;
}
.item {
background-color: #f8f8f8;
border: 1px solid #ccc;
padding: 5px;
margin-bottom: 5px;
cursor: move;
}
.dropzone {
background-color: #f8f8f8;
border: 1px dashed #ccc;
text-align: center;
line-height: 200px;
cursor: pointer;
}
```
JavaScript:
```javascript
const left = document.querySelector('.left');
const right = document.querySelector('.right');
const dropzone = document.querySelector('.dropzone');
let draggingItem = null;
let draggingItemIndex = -1;
let isDraggingFromLeft = false;
// 左侧拖拽事件处理函数
function dragStart(e) {
draggingItem = this;
draggingItemIndex = Array.from(this.parentNode.children).indexOf(this);
isDraggingFromLeft = true;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', this.outerHTML);
this.classList.add('dragging');
}
function dragEnd() {
draggingItem = null;
draggingItemIndex = -1;
isDraggingFromLeft = false;
this.classList.remove('dragging');
}
// 右侧拖拽事件处理函数
function dragOver(e) {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
this.classList.add('over');
}
function dragLeave() {
this.classList.remove('over');
}
function drop(e) {
e.preventDefault();
const item = document.createElement('div');
item.classList.add('item');
item.draggable = true;
item.innerHTML = e.dataTransfer.getData('text/html');
this.parentNode.insertBefore(item, this);
const dropzoneItems = Array.from(this.parentNode.children);
const itemIndex = dropzoneItems.indexOf(item);
const draggingItemElement = dropzoneItems[draggingItemIndex];
if (isDraggingFromLeft) {
draggingItemElement.parentNode.removeChild(draggingItemElement);
}
if (draggingItem !== item) {
if (itemIndex > draggingItemIndex) {
draggingItemElement.parentNode.insertBefore(draggingItemElement, item.nextSibling);
} else {
draggingItemElement.parentNode.insertBefore(draggingItemElement, item);
}
}
this.classList.remove('over');
}
// 左侧拖拽事件监听器
const items = document.querySelectorAll('.left .item');
items.forEach(item => {
item.addEventListener('dragstart', dragStart);
item.addEventListener('dragend', dragEnd);
});
// 右侧拖拽事件监听器
dropzone.addEventListener('dragover', dragOver);
dropzone.addEventListener('dragleave', dragLeave);
dropzone.addEventListener('drop', drop);
```
这个实现示例可以让左侧多个拖拽内容,拖拽其中一个DOM到右侧,右侧DOM判断拖拽到DOM内,未释放前可进行排序,右侧DOM可拖拽排序。
阅读全文