uniapp 左右拖动div换位
时间: 2023-07-19 20:38:34 浏览: 169
要实现左右拖动div换位的功能,可以使用uni-app自带的u-move组件。具体实现步骤如下:
1. 在页面中引入u-move组件。
```html
<template>
<u-move>
<div v-for="(item, index) in list" :key="index" class="item">{{ item }}</div>
</u-move>
</template>
<script>
import uMove from '@/components/u-move/u-move.vue'
export default {
components: {
uMove
},
data() {
return {
list: ['item1', 'item2', 'item3']
}
}
}
</script>
```
2. 在样式中定义.item的样式,并设置它的position属性为absolute。
```css
.item {
width: 100px;
height: 100px;
background-color: #ccc;
position: absolute;
top: 0;
left: 0;
}
```
3. 在u-move组件中添加touchstart、touchmove、touchend事件的处理函数,实现拖动效果。
```html
<template>
<div class="u-move" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd">
<slot></slot>
</div>
</template>
<script>
export default {
data() {
return {
startX: 0,
startY: 0,
moveX: 0,
moveY: 0,
endX: 0,
endY: 0,
currentIndex: -1
}
},
methods: {
touchStart(e) {
const touch = e.touches[0]
this.startX = touch.pageX
this.startY = touch.pageY
this.currentIndex = this.getItemIndex(e.target)
},
touchMove(e) {
const touch = e.touches[0]
this.moveX = touch.pageX
this.moveY = touch.pageY
const diffX = this.moveX - this.startX
const diffY = this.moveY - this.startY
if (Math.abs(diffX) > Math.abs(diffY)) {
e.preventDefault()
e.stopPropagation()
this.moveItem(diffX)
}
},
touchEnd(e) {
this.currentIndex = -1
},
getItemIndex(target) {
const itemList = this.$el.querySelectorAll('.item')
for (let i = 0; i < itemList.length; i++) {
if (itemList[i] === target) {
return i
}
}
return -1
},
moveItem(diffX) {
if (this.currentIndex < 0) {
return
}
const itemList = this.$el.querySelectorAll('.item')
const currentIndexLeft = itemList[this.currentIndex].offsetLeft
const currentIndexRight = currentIndexLeft + itemList[this.currentIndex].offsetWidth
if (diffX > 0) {
// 向右拖动
for (let i = 0; i < itemList.length; i++) {
if (i === this.currentIndex) {
continue
}
const itemLeft = itemList[i].offsetLeft
const itemRight = itemLeft + itemList[i].offsetWidth
if (itemLeft < currentIndexRight && itemRight > currentIndexLeft) {
// 交换位置
const temp = this.list[this.currentIndex]
this.$set(this.list, this.currentIndex, this.list[i])
this.$set(this.list, i, temp)
this.currentIndex = i
break
}
}
} else {
// 向左拖动
for (let i = itemList.length - 1; i >= 0; i--) {
if (i === this.currentIndex) {
continue
}
const itemLeft = itemList[i].offsetLeft
const itemRight = itemLeft + itemList[i].offsetWidth
if (itemLeft < currentIndexRight && itemRight > currentIndexLeft) {
// 交换位置
const temp = this.list[this.currentIndex]
this.$set(this.list, this.currentIndex, this.list[i])
this.$set(this.list, i, temp)
this.currentIndex = i
break
}
}
}
}
}
}
</script>
```
通过以上步骤,就可以实现uni-app中左右拖动div换位的功能了。
阅读全文