在很多时候我们都会用到scroll-view做上下滚动效果,当在做一些多元素组合效果的时候,我们可能会须要判断是否滚动到顶部的问题,通过我们都是通过@scroll事件监听来做的
问题总结:如果快速手动拉到顶部,得到的e.detail.scrollTop值不一定是0
测试代码:
<template>
<scroll-view scroll-y="true" class="scroll" @scroll="scroll">
<view class="item">1</view>
<view class="item item2">2</view>
<view class="item item3">3</view>
<view class="item item4">4</view>
</scroll-view>
</template>
<script>
export default{
data(){
return {
}
},
methods:{
scroll(e){
console.log(e.detail.scrollTop,e);
}
}
}
</script>
<style lang="scss">
.scroll{
height: 500rpx;
width: 750rpx;
}
.item{
width: 750rpx;
height: 200rpx;
background-color: #000000;
}
.item2{
background-color: #0000FF;
}
.item3{
background-color: #00BFFF;
}
.item4{
background-color: #18B566;
}
</style>
可以测试,快速拉顶的情况下,e.detail.scrollTop并不是0,所以通过这个来判断是否到顶部是不准确的

出现这样问题的原因就要看触发scroll事件的机制是什么样的,快速滚动跟慢速滚动触发scroll的数量是不一样的,可以看出触发的条件对滚动速度或时间是有限制的,所以会有这样的问题出现
那么怎么来准确的判断是否滚动到顶部呢?
这里我们可以使用滚动到顶部事情scrolltoupper,这个事情是可以正常触发的
完整代码:
<template>
<scroll-view scroll-y="true" class="scroll" @scroll="scroll" @scrolltoupper="scrolltoupper">
<view class="item">1</view>
<view class="item item2">2</view>
<view class="item item3">3</view>
<view class="item item4">4</view>
</scroll-view>
</template>
<script>
export default{
data(){
return {
}
},
methods:{
scroll(e){
console.log(e.detail.scrollTop,e);
},
scrolltoupper(e){
console.log("顶部了",e);
}
}
}
</script>
<style lang="scss">
.scroll{
height: 500rpx;
width: 750rpx;
}
.item{
width: 750rpx;
height: 200rpx;
background-color: #000000;
}
.item2{
background-color: #0000FF;
}
.item3{
background-color: #00BFFF;
}
.item4{
background-color: #18B566;
}
</style>
只要到了顶部,都会触发@scrolltoupper事件,这样就能解决是否到达顶部问题了~