uniApp页面滚动到指定位置

  • Post author:
  • Post category:uniapp




Html
<template>
	<view>
		<view class="topSel">
			<view class="nav">
				<view v-for="(item,navIndex) in nav" :key="navIndex" class="navList" :class="currentNav==navIndex? 'ac':''" @tap="selNav(navIndex)">{{item}}</view>
			</view>
		</view>
		<view class="Html">Html</view>
		<view class="Css">Css</view>
		<view class="Javascript">Javascript</view>
	</view>
</template>


Javascript
<script>
	export default {
		data() {
			return {
				nav: ["Html", "Css", "Javascript"],
				currentNav: 0,
				HtmlTop:0,
				JavascriptTop:0,
				CssTop:0
			};
		},
		onShow(){
			this.$Tool.getRect(".Html").then(res => {
				//此处减50是因为page设置了padding,依个人情况而定没设置则不需要减
				this.HtmlTop = res.top-50
			})
			this.$Tool.getRect(".Css").then(res => {
				this.CssTop = res.top-50
			})
			this.$Tool.getRect(".Javascript").then(res => {
				this.JavascriptTop = res.top-50
			})
		},
		methods: {
			selNav(index) {
				this.currentNav = index
				switch (index) {
					case 0:
						uni.pageScrollTo({
							scrollTop: this.HtmlTop
						})
						break;
					case 1:
						uni.pageScrollTo({
							scrollTop: this.CssTop
						})
						break;
					case 2:
						uni.pageScrollTo({
							scrollTop: this.JavascriptTop
						})
						break;
				}
			}
		}
	};
</script>


Css
<style lang="scss">
	page {
		padding-top: 100rpx;
	}

	.topSel {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100rpx;
		background-color: rgba(255,255,255,.2);
		.nav {
			display: flex;
			align-items: center;
			justify-content: space-between;
			width: 60%;
			margin: 0 auto;
			font-size: 31rpx;
			color: #666;
			line-height: 70rpx;
			.ac {
				border-bottom: 2px transparent solid;
				border-image: linear-gradient(to right, #ffb759, #ff3251) 1 10;
				color: #ff3251;
				line-height: 70rpx;
			}
		}
	}
	.Html{
		width: 750rpx;
		height: 2000rpx;
		background-color: #1CBBB4;
		color: #fff;
	}
	.Javascript {
		width: 750rpx;
		height: 2000rpx;
		background-color: pink;
		color: #fff;
	}
	.Css{
		width: 750rpx;
		height: 2000rpx;
		background-color: #00BFFF;
		color: #fff;
	}
</style>


Tips

1.this.$Tool.getRect()方法参考:

uniApp获取页面元素大小和位置


2.uni.createSelectorQuery().select()方法获取到的单位默认是px



版权声明:本文为csdn_yuan_原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。