微信小程式基於movable-view實現滑動刪除效果
阿新 • • 發佈:2020-01-10
基於movable-view實現的一種較為完美的滑動刪除效果
前言:用了很多去實現滑動刪除的效果,都不太盡如人意,最後用小程式官方專用滑動元件來實現,但是這個元件有一點坑,咱們慢慢道來
1、wxml佈局
<view class="list"> <view class="row" wx:for="{{list}}" wx:key="id"> <movable-area class="list_item"> <!-- 坑就在這裡,當你向右滑動一點點距離的時候它就停住了,不回去。坑 --> <movable-view class="itmem_wrap" direction="horizontal" inertia="{{true}}" out-of-bounds="{{true}}" x="{{item.x}}" damping="{{60}}" data-index="{{index}}" bind:touchstart="touchMoveStartHandle" bind:touchend="touchMoveEndHandle"> {{'滑動刪除' + item.id}} </movable-view> <view class="delete_wrap"> <view class="delete_btn">刪除</view> </view> </movable-area> </view> </view>
2、wxss(這裡我用的less佈局,佈局很重要)
page { background-color: #efefef; } .list { padding: 30rpx 30rpx 0; .row { width: 100%; overflow: hidden; margin-bottom: 30rpx; .list_item { border-radius: 12rpx; position: relative; left: -120rpx; width: calc(100% + 120rpx); height: 160rpx; .itmem_wrap { width: calc(100% - 120rpx); height: 100%; display: flex; align-items: center; justify-content: center; position: relative; left: 120rpx; z-index: 2; background-color: #fff; } .delete_wrap { position: absolute; right: 0; top: 0; width: 50%; height: 100%; background-color: rgb(219,54,54); display: flex; justify-content: flex-end; z-index: 1; .delete_btn { width: 120rpx; height: 100%; display: flex; justify-content: center; align-items: center; color: #fff; } } } } }
3、JavaScript
const app = getApp() Page({ data: { list: [{ id: 1 },{ id: 2 },{ id: 3 },{ id: 4 },{ id: 5 },{ id: 6 },{ id: 7 },{ id: 8 },{ id: 9 },{ id: 10 } ],startX: '',startY: '' },onLoad: function () { this.setListX(); },// 給每一項設定x值 setListX() { this.data.list.map(item => { item.x = 0; }) this.setData({ list: this.data.list }) },// 開始滑動 touchMoveStartHandle(e) { // 我們要記錄滑動開始的座標點,後面計算要用到 if (e.touches.length == 1) { this.setData({ startX: e.touches[0].clientX,startY: e.touches[0].clientY }); } },// 滑動事件處理,一次只能滑出一個刪除按鈕 為了防止滑動出現抖動,我們用滑動結束事件 touchMoveEndHandle: function (e) { var currentIndex = e.currentTarget.dataset.index,//當前索引 startX = this.data.startX,//開始X座標 startY = this.data.startY,//開始Y座標 touchMoveEndX = e.changedTouches[0].clientX,//滑動變化X座標 touchMoveEndY = e.changedTouches[0].clientY,//滑動變化Y座標 //獲取滑動角度 angle = this.angle({ X: startX,Y: startY },{ X: touchMoveEndX,Y: touchMoveEndY }); //滑動超過50度角 return,防止上下滑動觸發 if (Math.abs(angle) > 50) return; this.data.list.map((item,index) => { if (touchMoveEndX > startX) { // 右滑 if (index == currentIndex) item.x = 0; } else { // 左滑 item.x = -120 if (index != currentIndex) item.x = 0; } }) this.setData({ list: this.data.list }) },/** * 計算滑動角度 * start 起點座標 * end 終點座標 * Math.PI 表示一個圓的周長與直徑的比例,約為 3.14159;PI就是圓周率π,PI是弧度制的π,也就是180° */ angle: function (start,end) { var _X = end.X - start.X,_Y = end.Y - start.Y return 360 * Math.atan(_Y / _X) / (2 * Math.PI); } })
4、最終效果預覽
總結
以上所述是小編給大家介紹的微信小程式基於movable-view實現滑動刪除效果,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對我們網站的支援!
如果你覺得本文對你有幫助,歡迎轉載,煩請註明出處,謝謝!