小程序下滑触底,切换页面
作者:互联网
小程序项目需求,触底后上滑切换页面,下滑取消切换。
用到touch事件,分别绑定touchstart、touchmove、touchend事件
wxml代码
<view class="section" bindtouchstart="handletouchtart" bindtouchmove="handletouchmove" bindtouchend="handletouchend">
<view class='ul'>
<view class='' wx:for="list" wx:key="{{index}}">
<view wx:for="list" wx:key="{{index}}" class='li'>{{text}}{{pagenum}}</view>
</view>
</view>
</view>
<!-- 遮罩层 -->
<view class='dialog' hidden='{{ishidden}}'></view>
js代码
data: {
list: 10,
next: false,
lastX: 0,
lastY: 0,
text: "滑动事件",
cloheight: 0,
ishidden: true,
pagenum: 1
},
记录touch开始位置
handletouchtart: function (event) {
// 赋值
event.preventDefault
this.data.lastX = event.touches[0].pageX
this.data.lastY = event.touches[0].pageY
},
在touchmove事件中判断上滑还是下滑
handletouchmove (event) {
event.preventDefault
console.log(event)
let currentX = event.touches[0].pageX
let currentY = event.touches[0].pageY
let tx = currentX - this.data.lastX
let ty = currentY - this.data.lastY
if (Math.abs(tx) < Math.abs(ty)) {
//上下方向滑动
if (ty < 0) {
console.log('上滑', this.data.next)
if (this.data.next) {
this.setData({
ishidden: false
})
}
} else if (ty > 0) {
console.log('下滑', this.data.next)
this.setData({
next: false,
ishidden: true
})
}
}
//将当前坐标进行保存以进行下一次计算
this.data.lastX = currentX
this.data.lastY = currentY
},
touchend判断是否触底,切换页面
handletouchend(event){
event.preventDefault
if (this.data.next) {
console.log('下一页')
this.setData({
pagenum: Number(this.data.pagenum) +1
})
wx.redirectTo({
url: './index?num=' + this.data.pagenum
})
}else {
console.log('不切换')
}
this.setData({
ishidden: true
})
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
var that = this
that.setData({
next: true
})
console.log('触底', that.data.next)
},
wxss代码
page {
width: 100%;
height: 100%;
}
.ul {
width: 100%;
overflow-y: scroll;
}
.section {
width: 100%;
}
.li {
width:100%;
height: 200rpx;
background: #f0f0f0;
}
.dialog {
width: 100%;
height: 100%;
position: fixed;
left: 0;
top: 0;
background: rgba(000, 000, 000, .6);
z-index: 2;
}
也可以利用scroll-view组件实现,bindscrolltolower触底回调,但是用scroll-view组件的话要设定高度,否则滚动不生效
移动设备屏幕大小不一致,所以scroll-view高度不能写死
<scroll-view scroll-y="true" bindscrolltolower="lower" style="height:{{cloheight}}px;overflow-y: scroll;">
// 内容
</scroll-view>
在小程序onload事件获取可使用窗口高度
onLoad: function () {
var that = this
wx.getSystemInfo({
success(res) {
that.setData({ cloheight: res.windowHeight })
}
})
},
lower(){ // 触底
console.log(11)
var that = this
that.setData({
next: true
})
},
如有更好的解决方案,欢迎来撩
标签:log,console,触底,100%,next,切换,data,event,页面 来源: https://blog.csdn.net/weixin_45295253/article/details/98193258