【微信小程序】高仿微信的左滑删除效果

前言

在小程序中,实现相似微信左滑删除的效果,有些人可能会想到在view里用到touchstart,touchmove,touchend结合实现的。但这个有缺点,特别是在ios真机上,左滑时页面会上下滑动,用户体验emmm...或许须要增长disableScroll:true,但这个页面会被禁止滚动,或许里面再嵌scroll-view就能够实现的。但我要说的不是这个方案,小程序出了更佳的一个组件,就是movable-view,很好用,提供动画的过渡,提供滑动触发的x轴,能够用这个x轴做为判断的,比较方便~ios

图片发自简书App

xml

<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大点的,只是要容下内容和删除的容器的宽度

js

<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>
复制代码

wxss

<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>
复制代码
相关文章
相关标签/搜索