需求背景:
实际的项目开发之中,有很多所谓的奇葩需求,当工程量相对较大的时候去更换组件会显得特别麻烦和费时。我这次的需求因为某些特殊原因,更换组件后也无法实现需要达到的效果,所以最后只能监听滑动事件,相信你看了我的代码也能轻松搞定!
@touchstart="touchStart" @touchend="touchEnd" @touchcancel="touchCancel" 是主要的函数,写在你要监听的盒子上。文章来源:https://www.toymoban.com/news/detail-635039.html
<view class="swiper-title" @touchstart="touchStart" @touchend="touchEnd" @touchcancel="touchCancel">{{item.name}}</view>
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()创建一个动画效果并使用它!文章来源地址https://www.toymoban.com/news/detail-635039.html
到了这里,关于uniapp 微信小程序实现监听屏幕左右滑动实现tab标签切换效果的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!