uniapp拖拽元素更换位置代码
时间: 2023-09-05 15:14:00 浏览: 145
以下是一个简单的uniapp拖拽元素更换位置的代码示例:
1. 在template中定义元素列表:
```
<template>
<view>
<view class="item" v-for="(item, index) in items" :key="index" :style="{top: item.y+'px', left: item.x+'px'}"
@mousedown="dragStart(index)" @touchstart="dragStart(index)">
{{ item.text }}
</view>
</view>
</template>
```
2. 在script中定义元素列表和拖拽事件处理函数:
```
<script>
export default {
data() {
return {
items: [
{text: 'Item 1', x: 50, y: 50},
{text: 'Item 2', x: 150, y: 50},
{text: 'Item 3', x: 250, y: 50},
{text: 'Item 4', x: 50, y: 150},
{text: 'Item 5', x: 150, y: 150},
{text: 'Item 6', x: 250, y: 150},
],
dragIndex: -1,
dragX: 0,
dragY: 0,
};
},
methods: {
dragStart(index, event) {
this.dragIndex = index;
this.dragX = (event.type === 'mousedown' ? event.clientX : event.touches[0].clientX) - this.items[index].x;
this.dragY = (event.type === 'mousedown' ? event.clientY : event.touches[0].clientY) - this.items[index].y;
event.preventDefault();
},
dragMove(event) {
if (this.dragIndex >= 0) {
this.items[this.dragIndex].x = (event.type === 'mousemove' ? event.clientX : event.touches[0].clientX) - this.dragX;
this.items[this.dragIndex].y = (event.type === 'mousemove' ? event.clientY : event.touches[0].clientY) - this.dragY;
}
},
dragEnd() {
if (this.dragIndex >= 0) {
for (let i = 0; i < this.items.length; i++) {
if (i !== this.dragIndex && this.items[i].x < this.items[this.dragIndex].x + 50 && this.items[i].x + 50 > this.items[this.dragIndex].x
&& this.items[i].y < this.items[this.dragIndex].y + 50 && this.items[i].y + 50 > this.items[this.dragIndex].y) {
let temp = this.items[i];
this.$set(this.items, i, this.items[this.dragIndex]);
this.$set(this.items, this.dragIndex, temp);
break;
}
}
this.dragIndex = -1;
}
},
},
mounted() {
document.addEventListener('mousemove', this.dragMove);
document.addEventListener('mouseup', this.dragEnd);
document.addEventListener('touchmove', this.dragMove);
document.addEventListener('touchend', this.dragEnd);
},
beforeDestroy() {
document.removeEventListener('mousemove', this.dragMove);
document.removeEventListener('mouseup', this.dragEnd);
document.removeEventListener('touchmove', this.dragMove);
document.removeEventListener('touchend', this.dragEnd);
},
};
</script>
```
3. 在style中定义元素样式:
```
<style>
.item {
position: absolute;
width: 50px;
height: 50px;
background-color: #ccc;
border: 1px solid #000;
text-align: center;
line-height: 50px;
cursor: move;
}
</style>
```
这样,就可以实现元素拖拽更换位置的功能。当拖拽结束时,会检测当前拖拽元素是否与其他元素重叠,如果重叠则交换位置。
阅读全文