官方示例:uni-app官网
效果图:
实现代码:
<template>
<view>
<scroll-view :scroll-top="scrollTop" scroll-y="true" style="height: 300rpx;" @scrolltoupper="upper" @scrolltolower="lower" @scroll="scroll" scroll-with-animation="true" >
<view style="height: 200rpx;background-color: red;">A</view>
<view style="height: 200rpx;background-color: green;">B</view>
<view style="height: 200rpx;background-color: blue;">C</view>
</scroll-view>
<button @click="goTop()">点击这里返回顶部</button>
<scroll-view style="white-space: nowrap;width: 100%;" scroll-x="true" @scroll="scroll" scroll-left="120">
<view style="height: 300rpx;display: inline-block;
width: 70%;background-color: red;">A</view>
<view style="height: 200rpx;display: inline-block;
width: 70%;background-color: green">B</view>
<view style="height: 300rpx;display: inline-block;
width: 100%;background-color: blue">C</view>
</scroll-view>
</view>
</template>
<script>
export default {
data() {
return {
scrollTop: 0,
old: {
scrollTop: 0
}
}
},
methods: {
upper: function(e) {
console.log("滚动到顶部:",e)//滚动到顶部/左边,达到阈值会触发 scrolltoupper 事件
},
lower: function(e) {
console.log("滚动到底部:",e)//滚动到底部/右边,达到阈值会触发 scrolltolower 事件
},
scroll: function(e) {
console.log(e)
this.old.scrollTop = e.detail.scrollTop//滚动时触发,event.detail = {scrollLeft, scrollTop, scrollHeight, scrollWidth, deltaX, deltaY}
},
goTop: function(e) {
// 解决view层不同步的问题
this.scrollTop = this.old.scrollTop
this.$nextTick(function() {
this.scrollTop = 0
});
uni.showToast({
icon:"none",
title:"纵向滚动 scrollTop 值已被修改为 0"
})
}
}
}
</script>