js 左侧多个拖拽内容,拖拽其中一个dom到右侧,右侧dom判断拖拽到dom内,未释放前可进行排序,右侧dom可拖拽排序,请用完整class 类代码实现
时间: 2024-01-07 08:02:43 浏览: 73
一个js拖拽的效果类和dom-drag.js浅析
以下是一个简单的实现示例:
```html
<!-- 左侧拖拽内容区域 -->
<div class="left-content">
<div class="draggable" draggable="true">拖拽内容1</div>
<div class="draggable" draggable="true">拖拽内容2</div>
<div class="draggable" draggable="true">拖拽内容3</div>
</div>
<!-- 右侧拖拽排序区域 -->
<div class="right-content" droppable="true">
<div class="draggable" draggable="true">拖拽内容4</div>
<div class="draggable" draggable="true">拖拽内容5</div>
<div class="draggable" draggable="true">拖拽内容6</div>
</div>
```
```css
.left-content {
display: flex;
flex-wrap: wrap;
}
.right-content {
display: flex;
flex-wrap: wrap;
}
.draggable {
width: 100px;
height: 50px;
background-color: #ccc;
margin: 10px;
}
.draggable.dragging {
opacity: 0.5;
}
.droppable {
border: 2px dashed #333;
min-height: 100px;
}
```
```js
// 获取左侧和右侧的拖拽元素
const leftContent = document.querySelector('.left-content');
const rightContent = document.querySelector('.right-content');
const draggables = document.querySelectorAll('.draggable');
// 左侧拖拽元素开始拖动时
draggables.forEach(draggable => {
draggable.addEventListener('dragstart', () => {
draggable.classList.add('dragging');
});
});
// 左侧拖拽元素结束拖动时
draggables.forEach(draggable => {
draggable.addEventListener('dragend', () => {
draggable.classList.remove('dragging');
});
});
// 右侧容器拖拽事件
rightContent.addEventListener('dragover', e => {
e.preventDefault();
});
// 右侧容器释放拖拽元素时
rightContent.addEventListener('drop', e => {
e.preventDefault();
const draggable = document.querySelector('.dragging');
if (draggable && e.target.classList.contains('droppable')) {
// 将拖拽元素添加到右侧容器中
e.target.appendChild(draggable);
}
});
// 右侧拖拽元素开始拖动时
rightContent.addEventListener('dragstart', e => {
const draggable = e.target.closest('.draggable');
if (draggable) {
draggable.classList.add('dragging');
}
});
// 右侧拖拽元素结束拖动时
rightContent.addEventListener('dragend', e => {
const draggable = e.target.closest('.draggable');
if (draggable) {
draggable.classList.remove('dragging');
}
});
```
这个示例中,我们使用 `draggable` 和 `droppable` 属性来标记可以拖拽和释放的元素。在左侧拖拽元素时,我们给拖拽元素添加 `dragging` 类来显示拖拽过程中的样式。在右侧容器中,我们使用 `dragover` 和 `drop` 事件来处理拖拽释放。在右侧拖拽元素时,我们使用 `dragstart` 和 `dragend` 事件来处理拖拽过程中的样式。
阅读全文