uniapp 返回顶部功能实现

发布于:2023-01-22 ⋅ 阅读:(515) ⋅ 点赞:(0)

目录

scroll-view

代码演示

运行效果


scroll-view

可滚动视图区域。用于区域滚动。

需注意在webview渲染的页面中,区域滚动的性能不及页面滚动。

官网详情

属性说明 

属性名 类型 默认值 说明 平台差异说明
scroll-y Boolean false 允许纵向滚动
scroll-into-view String 值应为某子元素id(id不能以数字开头)。设置哪个方向可滚动,则在哪个方向滚动到该元素
scroll-with-animation Boolean false 在设置滚动条位置时使用动画过渡
@scroll EventHandle 滚动时触发,event.detail = {scrollLeft, scrollTop, scrollHeight, scrollWidth, deltaX, deltaY}

代码演示

<template>
	<scroll-view :scroll-into-view="data.topItem" scroll-with-animation="true" class="scroll-cont" scroll-y="true" @scroll="toShowBack">
		<!-- top 作为定位返回顶部的坐标 -->
		<view id="top"></view>
		<view class="bt">
			<img src="../../static/bt/bt-1.jpg">
		</view>
		<!-- 返回底部样式 -->
		<view class="show-back" v-if="data.isShow" @click="toBackTop()">
			<!-- 使用uni-ui图标 -->
			<uni-icons type="arrowthinup" size="30"></uni-icons>
		</view>
	</scroll-view>
</template>

<script setup>
import { reactive } from "vue";
	// 定义返回顶部功能参数
 const data=reactive({
	 isShow: false,
	 //返回顶部标记点
	 topItem: ""
 })
 //获取滚动参数 
 const toShowBack=(ev)=>{
	 let {scrollTop}=ev.detail;
	 //是否展示返回按钮实现
	 data.isShow=scrollTop>300;
	 //清理定位坐标 目的 让返回按钮可反复使用
	 data.topItem='';
 }
 //返回 定位
 const toBackTop=()=>{
	 data.topItem='top';
 }
</script>

<style lang="scss">
	.container {
		padding: 20px;
		font-size: 14px;
		line-height: 24px;
	}

	.show-back {
		height: 100upx;
		width: 100upx;
		background-color: #fff;
		// 圆角弧度 添加圆角边框
		border-radius: 50%;
		//盒子阴影
		box-shadow: 0 0 30upx 4upx rgba(0, 0, 0, 0.4);
		// position 属性规定元素的定位类型 fixed元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。
		position: fixed;
		bottom: 120upx;
		right: 20upx;
		text-align: center;
		line-height: 100upx;
	}
	//使用竖向滚动时,需要给 <scroll-view> 一个固定高度,通过 css 设置 height;使用横向滚动时,需要给<scroll-view>添加white-space: nowrap;样式。
	.scroll-cont{
		height: 100vh;
	}
</style>

运行效果

本文含有隐藏内容,请 开通VIP 后查看