uniapp,从父元素下拖拽一个子元素,到另一个父元素下,并加入这个父元素当中
时间: 2024-01-18 09:04:45 浏览: 32
在uniapp中,实现从父元素下拖拽一个子元素到另一个父元素中,并加入该父元素,可以将子元素的位置信息、父元素信息等存储在数据中,通过计算来实现拖拽效果。以下是一个简单的示例:
```html
<template>
<view class="container">
<view class="box" :style="boxStyle" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd">{{boxText}}</view>
<view class="target" :style="targetStyle" ref="target"></view>
</view>
</template>
<script>
export default {
data() {
return {
boxText: '拖拽我',
boxStyle: {
top: '50px',
left: '50px'
},
targetStyle: {
top: '200px',
left: '200px',
width: '200px',
height: '200px'
},
startPageX: 0,
startPageY: 0,
initBoxTop: 50,
initBoxLeft: 50,
parentRect: {},
targetRect: {}
}
},
methods: {
touchStart(e) {
this.startPageX = e.changedTouches[0].pageX
this.startPageY = e.changedTouches[0].pageY
this.initBoxTop = parseInt(this.boxStyle.top)
this.initBoxLeft = parseInt(this.boxStyle.left)
this.parentRect = uni.createSelectorQuery().select('.container').boundingClientRect()
this.targetRect = uni.createSelectorQuery().select('.target').boundingClientRect()
},
touchMove(e) {
let diffX = e.changedTouches[0].pageX - this.startPageX
let diffY = e.changedTouches[0].pageY - this.startPageY
this.boxStyle.top = this.initBoxTop + diffY + 'px'
this.boxStyle.left = this.initBoxLeft + diffX + 'px'
},
touchEnd(e) {
Promise.all([this.parentRect.exec(), this.targetRect.exec()]).then(res => {
let parentTop = res[0].top
let parentLeft = res[0].left
let parentWidth = res[0].width
let parentHeight = res[0].height
let targetTop = res[1].top
let targetLeft = res[1].left
let targetWidth = res[1].width
let targetHeight = res[1].height
let boxTop = parseInt(this.boxStyle.top)
let boxLeft = parseInt(this.boxStyle.left)
let boxWidth = 100
let boxHeight = 100
if (boxTop + boxHeight > targetTop && boxTop < targetTop + targetHeight && boxLeft + boxWidth > targetLeft && boxLeft < targetLeft + targetWidth) {
this.boxText = '成功拖拽到目标区域'
let newItem = {
id: new Date().getTime(),
top: boxTop - parentTop - targetTop + 'px',
left: boxLeft - parentLeft - targetLeft + 'px'
}
this.$set(this.$refs.target.$children[0], 'items', [...this.$refs.target.$children[0].items, newItem])
} else {
this.boxText = '拖拽我'
this.boxStyle.top = '50px'
this.boxStyle.left = '50px'
}
})
}
}
}
</script>
<style>
.container {
position: relative;
width: 100%;
height: 100%;
}
.box {
position: absolute;
width: 100px;
height: 100px;
background-color: #ccc;
text-align: center;
line-height: 100px;
}
.target {
position: absolute;
width: 200px;
height: 200px;
top: 200px;
left: 200px;
border: 1px solid #000;
}
.item {
position: absolute;
width: 100px;
height: 100px;
background-color: green;
text-align: center;
line-height: 100px;
}
</style>
```
以上代码实现了一个拖拽效果,当拖拽元素移动到目标区域时,会提示拖拽成功,并将拖拽的元素加入到目标区域中。您可以根据自己的需求进行修改。