uniapp中回到顶部的两种方式
一般情况下
如果只是一般情况下,可以使用uni.pageScrollTo直接解决,如下
1 2 3 4
| uni.pageScrollTo({ scrollTop: 0, duration: 300 })
|
详细的代码组合如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| <template> <view> <!-- 回到顶部按钮 --> <view class="back-btn" @click="toTop" v-if="isShowTop"> <image src="../static/icon/top.png" class="back-btn_img"> </view> </view> </template>
<script> export default { data() { return { // 是否展示回到顶部按钮 isShowTop: false } }, onPageScroll(e) { // 当页面滚动高度大于200时,显示回到顶部按钮 if (e.scrollTop > 200) { this.isShowTop = true } else { this.isShowTop = false } }, methods: { // 回到页面顶部 toTop() { uni.pageScrollTo({ scrollTop: 0, duration: 300 }) } } } </script> <style> /* 回到顶部按钮 */ .back-btn { z-index: 99; /* 置于最上层 */ position: fixed; right: 40rpx; bottom: 150rpx; color: gray; .back-btn_img { width: 70rpx; height: 70rpx; } } </style>
|
在使用scroll-view时,我发现页面中的onPageScroll和uni.pageScrollTo居然失效了,用了很多方法都没用,所以这里我直接用scroll-view来做
- 使用**@scroll-top**来回到顶部
- 使用**@scroll**来侦测滚动位置
具体代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| <template> <view> <!-- 区域滚动 --> <scroll-view :scroll-top="scrollTop" scroll-y="true" @scroll="showHeight"> </scroll-view> <!-- 回到顶部按钮 --> <view class="back-btn" @click="toTop"> <image src="../../static/icon/top.png" class="back-btn_img"> </view> </view> <template> <script> export default { data() { return { // 是否展示回到顶部按钮 isShowTop: false, // 页面高度 scrollTop: 0, old: { scrollTop: 0 } } }, methods: { // 滚动 showHeight(e) { // 滚动高度好过两百 if (e.detail.scrollTop) { this.isShowTop = true } else { this.isShowTop = false } this.old.scrollTop = e.detail.scrollTop }, // 回到页面顶部 toTop(e) { this.scrollTop = this.old.scrollTop this.$nextTick(function() { this.scrollTop = 0 }); }, } } </script> <style lang="scss"> /* 回到顶部按钮 */ .back-btn { z-index: 99; /* 置于最上层 */ position: fixed; right: 40rpx; bottom: 150rpx; color: gray;
.back-btn_img { width: 70rpx; height: 70rpx; } } </style>
|
代码中的图片可以在iconfont中去下载