在小程序中,實現相似微信左滑刪除的效果,有些人可能會想到在view裏用到touchstart,touchmove,touchend結合實現的。但這個有缺點,特別是在ios真機上,左滑時頁面會上下滑動,用戶體驗emmm...或許須要增長disableScroll:true,但這個頁面會被禁止滾動,或許裏面再嵌scroll-view就能夠實現的。但我要說的不是這個方案,小程序出了更佳的一個組件,就是movable-view,很好用,提供動畫的過渡,提供滑動觸發的x軸,能夠用這個x軸做爲判斷的,比較方便~ios
<template>
<block wx:for="{{dataList}}" wx:key="index">
<movable-area class="area">
<movable-view class="item"
damping="100"
direction="horizontal"
x="{{item.swipeX}}"
data-index="{{index}}"
@change="swipeChange({{index}})"
out-of-bounds="true"
animation="true"
@touchend="swipeEnd({{index}})"
@touchstart="swipeStart({{index}})"
>
<view class="item-left">{{item.name}}</view>
<view class="item-right" @tap.stop="delete({{index}})">刪除</view>
</movable-view>
<view class="line"></view>
</movable-area>
</block>
</template>
複製代碼
- Tip:movable,movaview必須設置寬和高的值,不然默認值(10px)
- Tip: movable必需要比movaview大點的,只是要容下內容和刪除的容器的寬度
<script>
import wepy from 'wepy';
export default class swipeLeft extends wepy.page{
config={
navigationBarTitleText:'左滑刪除',
}
data={
dataList:[
{name:'迫不得已花落去'},
{name:'莊生曉夢迷蝴蝶'},
{name:'天涯何處無芳草'},
{name:'此情可待成追憶'},
{name:'人面不知何處'},
{name:'心悅君兮君不知'}
],
currentX:0,
currentIndex:-1,
}
setShowDel(index,moveX){
this.dataList[index].swipeX=moveX;
}
methods={
//滑動開始的觸發事件
swipeStart(index){
this.currentIndex=index;
this.dataList.forEach((item,i)=>{
if(index!=i){
item.swipeX=0;
}
})
},
//滑動結束的觸發事件
swipeEnd(index){
let swipeX=this.dataList[index].swipeX;
if(this.currentX<-10 && (swipeX===0 || !swipeX)){
this.setShowDel(index,-120);
return;
}
if(this.currentX>-55 && swipeX===-120){
this.setShowDel(index,0);
return;
}
},
//監聽滑動過程觸發的事件
swipeChange(...e){
if(this.currentIndex===e[0]){
this.currentX=e[1].detail.x;
}
}
}
}
</script>
複製代碼
<style lang="less">
.area{
width: 750rpx;
position: relative;
height: 150rpx;
.line{
position: absolute;
width: 690rpx;
height: 1px;
background: #ededed;
bottom: 0;
left: 50%;
transform: translateX(-50%);
z-index: -1;
}
.item{
width: 900rpx;
height: 150rpx;
display: flex;
align-items: center;
.item-left{
width: 750rpx;
margin-left: 30rpx;
}
.item-right{
width: 140rpx;
height: 150rpx;
background: #ED6F20;
color: #fff;
line-height: 150rpx;
text-align: center;
border-radius: 0 10rpx 10rpx 0;
}
}
}
</style>
複製代碼