做了一个小程序的 movable-area 组件做的一个拖动功能,可能是我比较笨,逻辑我想了一个星期才有点起色,终于是 弄好了,
废话少说,上代码。
<view class="section">
<movable-area class="area" >
<movable-view class='cent' wx:for="{{list}}" x="{{item.x}}" y="{{item.y}}"
data-index="{{index}}" bindtouchstart='start' bindtouchend='end' bindtouchmove='move' direction="vertical">
{{item.id}}</movable-view>
</movable-area>
</view>
.section{
width: 100%;
height: 100vh;
}
.area{
height: 100vh;
width: 100%;
background-color: white;
}
.cent{
color: white;
display: flex;
align-items: center;
justify-content: center;
background-color: #ccc;
border: solid 1rpx #7c7c7c;
height: 100rpx;
width: 99.5%;
}
// pages/test/test2.js
Page({
/**
* 页面的初始数据
*/
data: {
x: 0,
y1: 0,
y2: 0,
yb: 0,
list: [{
id: 1,
x: 0,
y: 0,
},
{
id: 2,
x: 0,
y: 60,
},
{
id: 3,
x: 0,
y: 120,
},
{
id: 4,
x: 0,
y: 180,
},
]
},
start: function(e) {
console.log("点击", e)
let that = this,
list = that.data.list,
index = e.currentTarget.dataset.index,
y2 = e.changedTouches[0].pageY - list[index].y;
console.log(index);
that.setData({
yb: index,
y1: e.changedTouches[0].pageY,
y2: y2
})
},
move: function(e) {
let that = this,
py = e.changedTouches[0].pageY,
index = e.currentTarget.dataset.index,
list = that.data.list,
y1 = that.data.y1,
y2 = that.data.y2,
y4 = parseInt(py / 60),
yb = that.data.yb;
list[index].y = py - y2;
if (y4 > list.length - 1) {
y4 = list.length - 1;
}
if (y4 < index || yb < index) {
// console.log("上移");
if (yb > y4) list[y4].y = (y4 + 1) * 60;
if (yb < y4) list[yb].y = (y4 - 1) * 60;
}
if (y4 > index || yb > index) {
//console.log("下移");
if (yb > y4) list[yb].y = yb * 60;
if (yb < y4) list[y4].y = (y4 - 1) * 60;
}
that.setData({
yb: y4,
list: list
})
},
end: function(e) {
let that = this,
index = e.currentTarget.dataset.index,
py = e.changedTouches[0].pageY,
y1 = that.data.y1,
y2 = that.data.y2,
list = that.data.list,
y4 = parseInt(py / 60);
// console.log("y4",y4);
if (y4 > list.length - 1) {
y4 = list.length - 1;
}
list[index].y = y4 * 60;
console.log("endlist", list);
for (let i = 0; i < list.length - 1; i++) {
for (let j = 0; j < list.length - 1 - i; j++) // j开始等于0,
{
if (list[j].y > list[j + 1].y) {
let temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
}
}
}
that.setData({
list: list
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
wx.setNavigationBarTitle({
title: options.title,
success: function(res) {
// success
}
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function() {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function() {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function() {
}
})
代码可以直接拖到小程序测试,想要完善,得自己改样式。