使用uniapp框架实现根据手势滑动切换图片等

有时候我们要根据数据左右滑动切换某个内容,并不是像swiper轮播图那样

这个时候就需要我们封装一个组件了

先看一下具体思路

    1.给容器绑定两个触屏事件 @touchstart和@touchend
	2.用户按下屏幕事件
	  1.记录用户按下屏幕的时间,Date.now()时间戳 返回 1970-1-1到现在的毫秒数
	  2.记录用户按下屏幕的坐标 x 和 y
	3.用户离开屏幕事件
	  1.记录用户离开屏幕的时间 Date.now()
	  2.记录用户离开屏幕的坐标 x 和 y
	  3.根据两个时间 运算 判断 用户按下屏幕时长是否合法
	  4.根据两对坐标 判断距离是否合法 判断 滑动的方向

具体代码

<view
	@touchstart="handleTouchstart"
	@touchend="handleTouchend">
		
	</view>

export default{
		data(){
			return {
				//按下的时间
				startTime:0,
				//按下的坐标
				startX:0,
				startY:0
			}
		},
	methods:{
		//手指按下屏幕
		handleTouchstart(event){
			
			
			this.startTime = Date.now()
			this.startX = event.changedTouches[0].clientX
			this.startY = event.changedTouches[0].clientY
		},
		//手指离开屏幕
		handleTouchend(event){
			
			const endTime = Date.now()
			const endX = event.changedTouches[0].clientX
			const endY = event.changedTouches[0].clientY
			
			//判断按下的时长
			if(endTime - this.startTime >2000){
				return
			}
			//滑动的方向
			let direction = "";
			//先判断用户滑动的距离,是否合法,合法:判断滑动的方向 注意 距离要加上绝对值
			if(Math.abs(endX -this.startX)>10){
				//滑动方向
				direction = endX -this.startX >0?"right":"left"
			}else{
				return
			}
			//用户做了合法的滑动操作
			console.log(direction)
			
			this.$emit('swiperAction',{direction})
		}
	}
}

因为我这个是图片之间的切换,所以发送事件到父组件进行操作

<swiperaction @swiperAction="handleSwiperAction">
	<image :src="imgDetail.thumb" mode="widthFix"></image>
</swiperaction>

data(){
		return{
			imgDetail:{},
			imgIndex:0
		}  
	},

onLoad() {
		// console.log(getApp().globalData)
		const {imgIndex} = getApp().globalData
		this.imgIndex = imgIndex
		this.getImg()
	},
methods:{
  getImg(){
			const {imgList} = getApp().globalData
			this.imgDetail = imgList[this.imgIndex]
		},
}

handleSwiperAction(e){
	console.log(e)
	// 1.用户左滑 imgIndex++
	// 2.用户右滑 imgIndex--
	// 3.判断 数组是否越界问题
	// 4.左滑 e.direction ==="left"&&this.imgIndex<imgList.length-1
	// 5.右滑 e.direction ==="right"&&this.imgIndex>0
	const {imgList} = getApp().globalData
	if(e.direction ==="left"&&this.imgIndex<imgList.length-1){
	//可以进行左滑
	this.imgIndex++
	this.getImg()
	}else if(e.direction ==="right"&&this.imgIndex>0){
	this.imgIndex--
	this.getImg()
		}else{
				uni.showToast({
					title:"没有数据了",
					icon:"none"
				})
			}
		}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值