Skip to content

BackTop 返回顶部

该组件一个用于长页面,滑动一定距离后,出现返回顶部按钮,方便快速返回顶部的场景。

平台差异说明

App(vue)App(nvue)H5小程序

基本使用

由于返回顶部需要实时监听滚动条的位置,从而判断返回的按钮该出现还是隐藏,由于组件无法得知页面的滚动条信息,只能在页面onPageScroll生命周期 中获得滚动条的位置,故需要在页面监听onPageScroll生命周期,实时获得滚动条的位置,通过Props传递给组件。

html
<template>
	<view class="wrap">
		<text>滑动页面,返回顶部按钮将出现在右下角</text>
		<up-back-top :scroll-top="scrollTop"></up-back-top>
	</view>
</template>
js
<script setup>  
import { ref } from 'vue';  
import { onPageScroll } from '@dcloudio/uni-app';
  
// 创建响应式数据 scrollTop  
const scrollTop = ref(0);  
  
// onPageScroll 方法来更新 scrollTop 的值  
onPageScroll((e) => {
	scrollTop.value = e.scrollTop;
});
</script>
js
<script>
export default {
	data() {
		return {
			scrollTop: 0
		}
	},
	onPageScroll(e) {
		this.scrollTop = e.scrollTop;
	}
};
</script>
css
<style lang="scss" scoped>
	.wrap {
		height: 200vh;
	}
</style>

改变返回顶部按钮的出现时机

可以通过top参数,修改页面滚动多少距离时,出现返回顶部的按钮

html
<up-back-top :scroll-top="scrollTop" top="600"></up-back-top>

自定义返回顶部的图标和提示

  • 通过icon修改返回顶部按钮的图标,可以是uview-ultra内置的图标,或者图片路径
  • 通过text参数修改返回顶部按钮的文字提示信息,如果需要修改文字的颜色和大小,可以通过customStyle参数
html
<up-back-top :scroll-top="scrollTop" icon="arrow-up" text="返回"></up-back-top>

其他自定义样式

  • 通过iconStyle参数自定义图标的样式,比如颜色,大小等
  • 通过customStyle修改返回按钮的背景颜色,大小等
  • 通过mode修改按钮的形状,circle为圆形,square为方形

注意:如果通过icon参数传入图片路径的话,需要通过iconStyle参数设置图片的widthheight属性

html
<template>
	<view class="wrap">
		<text>滑动页面,返回顶部按钮将出现在右下角</text>
		<up-back-top :scrollTop="scrollTop" :mode="mode" :iconStyle="iconStyle"></up-back-top>
	</view>
</template>
js
<script setup>  
import { ref, reactive } from 'vue';  
import { onPageScroll } from '@dcloudio/uni-app';

// 使用 ref 创建响应式基本类型数据  
const scrollTop = ref(0);  
const mode = ref('square');  
  
// 使用 reactive 创建响应式对象数据  
const iconStyle = reactive({  
  fontSize: '32rpx',  
  color: '#2979ff'  
});  
  
// onPageScroll 方法来更新 scrollTop 的值  
onPageScroll((e) => {
	scrollTop.value = e.scrollTop;
}); 
</script>
js
<script>
export default {
	data() {
		return {
			scrollTop: 0,
			mode: 'square',
			iconStyle: {
				fontSize: '32rpx',
				color: '#2979ff'
			}
		}
	},
	onPageScroll(e) {
		this.scrollTop = e.scrollTop;
	}
};
</script>
css
<style lang="scss" scoped>
	.wrap {
		height: 200vh;
	}
</style>

右侧演示页面源代码地址

点击以下链接以查看右侧演示页面的源码


 github  gitee

API

Props

参数说明类型默认值可选值
mode按钮形状Stringcirclesquare
iconuview-ultra内置图标名称,或图片路径Stringarrow-upward-
text返回顶部按钮的提示文字String--
duration返回顶部过程中的过渡时间,单位msString | Number100-
scrollTop页面的滚动距离,通过onPageScroll生命周期获取String | Number0-
top滚动条滑动多少距离时显示,单位rpxString | Number400-
bottom返回按钮位置到屏幕底部的距离,单位rpxString | Number100-
right返回按钮位置到屏幕右边的距离,单位rpxString | Number20-
z-index返回顶部按钮的层级String | Number9-
iconStyle图标的样式,对象形式Object--
customStyle按钮外层的自定义样式Object--

Slot

名称说明
-自定义返回按钮的所有内容