用vue实现图片在两个区域内互相拖拽区域内图片排列要整齐
以下是一个简单的实现,实现了图片在两个区域内互相拖拽,并且在区域内排列整齐。
HTML代码:
<div id="app">
<div class="container">
<h2>区域1</h2>
<div class="image-container" @dragover.prevent @drop="dropImage(1)">
<div v-for="(image, index) in images1" :key="index" class="image" :style="{ backgroundImage: 'url(' + image + ')' }" draggable="true" @dragstart="dragStart(index, 1)" @dragend="dragEnd"></div>
</div>
</div>
<div class="container">
<h2>区域2</h2>
<div class="image-container" @dragover.prevent @drop="dropImage(2)">
<div v-for="(image, index) in images2" :key="index" class="image" :style="{ backgroundImage: 'url(' + image + ')' }" draggable="true" @dragstart="dragStart(index, 2)" @dragend="dragEnd"></div>
</div>
</div>
</div>
CSS代码:
.container {
margin: 20px;
padding: 20px;
border: 1px solid #ccc;
}
.image-container {
display: flex;
flex-wrap: wrap;
}
.image {
width: 100px;
height: 100px;
margin: 10px;
background-size: cover;
background-position: center;
cursor: move;
}
JavaScript代码:
new Vue({
el: '#app',
data: {
images1: [
'https://picsum.photos/id/1/100/100',
'https://picsum.photos/id/2/100/100',
'https://picsum.photos/id/3/100/100',
'https://picsum.photos/id/4/100/100',
'https://picsum.photos/id/5/100/100'
],
images2: []
},
methods: {
dragStart(index, area) {
this.draggedImage = { index, area };
},
dragEnd() {
this.draggedImage = null;
},
dropImage(area) {
if (this.draggedImage.area !== area) {
const image = this.draggedImage.area === 1 ? this.images1.splice(this.draggedImage.index, 1) : this.images2.splice(this.draggedImage.index, 1);
this.images2.push(image[0]);
}
}
}
});
实现思路:
-
在HTML中,创建两个区域,每个区域都有一个包含图片的容器。容器使用flex布局,并设置图片的大小、间距等样式。
-
在Vue实例中,定义两个数组images1和images2,分别存储两个区域的图片。同时,定义一个draggedImage变量,用于记录正在拖拽的图片。
-
在容器中的每个图片元素上,使用draggable属性使其可拖拽,并绑定dragstart和dragend事件。在dragstart事件中,记录正在拖拽的图片的索引和所在区域。在dragend事件中,将draggedImage变量设为null。
-
在容器上绑定dragover和drop事件。在dragover事件中,调用prevent方法阻止默认行为。在drop事件中,判断拖拽的图片所在区域和放置的区域是否相同。如果不同,从原区域的数组中移除图片,并将其添加到目标区域的数组中。
-
在容器中使用v-for指令渲染图片元素,使用backgroundImage样式设置图片的背景。在样式中使用backgroundSize和backgroundPosition属性使图片居中并填满容器。使用cursor样式设置鼠标形状为move。
这样,就可以实现图片在两个区域内互相拖拽,并且在区域内排列整齐。
原文地址: https://www.cveoy.top/t/topic/Zwf 著作权归作者所有。请勿转载和采集!