小程式拖動排序
阿新 • • 發佈:2018-12-16
做了一個小程式的 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() { } })
程式碼可以直接拖到小程式測試,想要完善,得自己改樣式。