uniapp 微信小程序实现监听屏幕左右滑动实现tab标签切换效果

需求背景:

        实际的项目开发之中,有很多所谓的奇葩需求,当工程量相对较大的时候去更换组件会显得特别麻烦和费时。我这次的需求因为某些特殊原因,更换组件后也无法实现需要达到的效果,所以最后只能监听滑动事件,相信你看了我的代码也能轻松搞定!

         @touchstart="touchStart" @touchend="touchEnd" @touchcancel="touchCancel" 是主要的函数,写在你要监听的盒子上。

{{item.name}}
		data() {
			return {
				minOffset: 50, //最小偏移量,低于这个值不响应滑动处理
				minTime: 60, // 最小时间,单位:毫秒,低于这个值不响应滑动处理
				startX: 0, //开始时的X坐标
				startY: 0, //开始时的Y坐标
				startTime: 0, //开始时的毫秒数
				animationData: {},
			};
		},
touchStart(e) {
				// console.log('touchStart', e)
				this.startX = e.touches[0].pageX; // 获取触摸时的x坐标  
				this.startY = e.touches[0].pageY; // 获取触摸时的x坐标
				this.startTime = new Date().getTime(); //获取毫秒数
			},
			touchCancel: function(e) {
				this.startX = 0; //开始时的X坐标
				this.startY = 0; //开始时的Y坐标
				this.startTime = 0; //开始时的毫秒数
			},
			touchEnd: function(e) {
				// console.log('touchEnd', e)
				var endX = e.changedTouches[0].pageX;
				var endY = e.changedTouches[0].pageY;
				var touchTime = new Date().getTime() - this.startTime; //计算滑动时间
				//开始判断
				//1.判断时间是否符合
				if (touchTime >= this.minTime) {
					//2.判断偏移量:分X、Y
					var xOffset = endX - this.startX;
					var yOffset = endY - this.startY;
					// console.log('xOffset', xOffset)
					// console.log('yOffset', yOffset)
					//①条件1(偏移量x或者y要大于最小偏移量)
					//②条件2(可以判断出是左右滑动还是上下滑动)
					if (Math.abs(xOffset) >= Math.abs(yOffset) && Math.abs(xOffset) >= this.minOffset) {
						//左右滑动
						//③条件3(判断偏移量的正负)
						if (xOffset < 0) {
							// console.log('向左滑动 下一页')
							if(this.current + 1 < this.tabList.length) {
								this.current ++
								this.animation.translateX(-190).step()
							}else return
						} else {
							// console.log('向右滑动')
							if(this.current > 0) {
								this.current --
								if(this.current > 1) this.animation.translateX(190).step()
							}else return
						}
						this.change(this.current)
						this.animationData = this.animation.export()
					} else if (Math.abs(xOffset) < Math.abs(yOffset) && Math.abs(yOffset) >= this.minOffset) {
						//上下滑动
						//③条件3(判断偏移量的正负)
						if (yOffset < 0) {
							// console.log('向上滑动')
						} else {
							// console.log('向下滑动')
						}
					}
				} else {
					// console.log('滑动时间过短', touchTime)
				}
			},

        this.animation.translateX(190).step() 是动画效果和监听滑动无关,如果你想效果更好也可以像我一样在onLoad中使用uni.createAnimation()创建一个动画效果并使用它!

你可能感兴趣的:(uni-app,微信小程序,小程序)