1.创建一个容器 用moveabe-area标签包裹
html
<movable-area class='area'>
<view class="container_image">
<view wx:for="{{imageObj}}" wx:key="index" class="my_image" data-index='{{index}}' >
<image src="{{item.img}}" mode="" />
</view>
</view>
</movable-area>
css
.area{
width: 100%;
height: 400px;
background: yellow;
}
.container_image{
display: flex;
flex-wrap: wrap;
}
.my_image{
width: 200rpx;
height: 200rpx;
}
.my_image image{
width: 100%;
height: 100%;
}
js中data
Page({
data: {
//图片资源
imageObj: [
{ id: 1, img: "/static/stone.png" },
{ id: 2, img: "/static/sun.png" },
{ id: 3, img: "/static/water.png" },
{ id: 4, img: "/static/sun.png" },
{ id: 5, img: "/static/water.png" },
],
x: 0,
y: 0,
curIndex: 0,
hidden: true
},
2.遍历过后给每个item绑定事件 movable-view 长按时改变hidden值显示当前长按图片
在onLoad中调用loadData 获取item中每个图片在视图的位置 卡牌的宽高
<view class="container_image">
<view wx:for="{{imageObj}}" wx:key="index" class="my_image" data-index='{{index}}' bindlongpress='longtap' bindtouchend='touchend' bindtouchmove='touchm'>
<image src="{{item.img}}" mode="" />
</view>
</view>
<movable-view class='my_item' direction='all' inertia out-of-bounds="{{false}}" x="{{x}}" y="{{y}}" damping="{{10000}}" friction="{{1}}">
<view hidden='{{hidden}}' class='my_image'>
<image src="{{imageObj[curIndex]['img']}}"></image>
</view>
</movable-view>
/**
* 计算图片的宽高和位置
*/
loadData() {
const query = this.createSelectorQuery();
query.selectAll(".my_image").fields({
dataset: true,
rect: true
}, (result) => {
this.setData({
elements: result
});
}).exec();
//获取所有图片的宽高
query.selectAll('.my_image').boundingClientRect(rect => {
this.setData({
card_imgHeight: rect[0].height,
card_imgWidth: rect[0].width
})
}).exec();
},
/**
* 长按事件
* @param {*} e
*/
longtap(e) {
this.setData({
curIndex: e.currentTarget.dataset.index,
hidden: false,
//减去一半宽高获取图片中间位置
x: e.touches[0].pageX - (this.data.card_imgWidth / 2),
y: e.touches[0].pageY - (this.data.card_imgHeight / 2),
})
},
3.触摸结束交换图片
/**
* 触摸结束
* @param {*} e
*/
touchend: function (e) {
//当前点击的x坐标
const x = e.changedTouches[0].pageX
//当前点击的y坐标
const y = e.changedTouches[0].pageY;
//每个item在视图中的位置坐标
const list = this.data.elements;
//list列表
let data = this.data.imageObj
// 移动位置
for (let j = 0; j < list.length - 1; j++) {
const item = list[j];
console.log(item);
if (x > item.left && x < item.right && y > item.top && y < item.bottom) {
const endIndex = item.dataset.index;
const beginIndex = this.data.curIndex;
console.log('beginIndex',beginIndex,endIndex);
//向后移动
if (beginIndex < endIndex) {
let tem = data[beginIndex];
for (let i = beginIndex; i < endIndex; i++) {
console.log('向后移动',i);
data[i] = data[i + 1]
}
data[endIndex] = tem;
}
//向前移动
if (beginIndex > endIndex) {
let tem = data[beginIndex];
for (let i = beginIndex; i > endIndex; i--) {
console.log('向前移动',i);
data[i] = data[i - 1]
}
data[endIndex] = tem;
}
this.setData({
imageObj: this.data.imageObj
})
}
}
this.setData({
hidden: true
})
},