需求背景:
? ? ? ? 實際的項目開發(fā)之中,有很多所謂的奇葩需求,當(dāng)工程量相對較大的時候去更換組件會顯得特別麻煩和費時。我這次的需求因為某些特殊原因,更換組件后也無法實現(xiàn)需要達到的效果,所以最后只能監(jiān)聽滑動事件,相信你看了我的代碼也能輕松搞定!
?????????@touchstart="touchStart" @touchend="touchEnd" @touchcancel="touchCancel" 是主要的函數(shù),寫在你要監(jiān)聽的盒子上。文章來源:http://www.zghlxwxcb.cn/news/detail-635039.html
<view class="swiper-title" @touchstart="touchStart" @touchend="touchEnd" @touchcancel="touchCancel">{{item.name}}</view>
data() {
return {
minOffset: 50, //最小偏移量,低于這個值不響應(yīng)滑動處理
minTime: 60, // 最小時間,單位:毫秒,低于這個值不響應(yīng)滑動處理
startX: 0, //開始時的X坐標(biāo)
startY: 0, //開始時的Y坐標(biāo)
startTime: 0, //開始時的毫秒數(shù)
animationData: {},
};
},
touchStart(e) {
// console.log('touchStart', e)
this.startX = e.touches[0].pageX; // 獲取觸摸時的x坐標(biāo)
this.startY = e.touches[0].pageY; // 獲取觸摸時的x坐標(biāo)
this.startTime = new Date().getTime(); //獲取毫秒數(shù)
},
touchCancel: function(e) {
this.startX = 0; //開始時的X坐標(biāo)
this.startY = 0; //開始時的Y坐標(biāo)
this.startTime = 0; //開始時的毫秒數(shù)
},
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(判斷偏移量的正負(fù))
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(判斷偏移量的正負(fù))
if (yOffset < 0) {
// console.log('向上滑動')
} else {
// console.log('向下滑動')
}
}
} else {
// console.log('滑動時間過短', touchTime)
}
},
????????this.animation.translateX(190).step() 是動畫效果和監(jiān)聽滑動無關(guān),如果你想效果更好也可以像我一樣在onLoad中使用uni.createAnimation()創(chuàng)建一個動畫效果并使用它!文章來源地址http://www.zghlxwxcb.cn/news/detail-635039.html
到了這里,關(guān)于uniapp 微信小程序?qū)崿F(xiàn)監(jiān)聽屏幕左右滑動實現(xiàn)tab標(biāo)簽切換效果的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!