使用uniapp框架实现小程序的锚点跳转以及滚动监听

主要利用了scroll-view里面的属性

一.首先是静态布局

<template>
<view class="ld">
	<view class="left">
		<view v-for="(item,index) in list" :key="index"
		:class="{active:currentIndex==index}"
		@click="changeactive(index)">{{item.title}}</view>
	</view>
	<view class="right">
		<scroll-view scroll-y="true" 
		             style="height: 200px;"
					 :scroll-into-view="doms"
					 scroll-with-animation
					 @scroll="scrolls"
					 @scrolltolower="scrolltolower">
		<view v-for="(items,index) in list" :key="index" :id="'po'+index" class="title">
		<view class="titlecolor">{{items.title}}</view>
		<view  v-for="(it,index) in items.list" :key="index">{{it}}</view>
		</view>
		</scroll-view>
	</view>
</view>

二.script中的内容

export default {
	data() {
		return {
			list:[
				{title:"中餐",list:['盖饭','扒饭','鸡骨头','鸡肉']},
				{title:"西餐",list:['牛排','羊排','鸡排','猪排']},
				{title:"南餐",list:['胡萝卜','青椒','炒鸡蛋','西虹市']},
				{title:"北餐",list:['锅包肉','肉包','杀猪菜','血肠']}
			],
			currentIndex:0,
			doms:'',
			topList:[]
		}
	},
	onLoad() {

	},
	onReady(){
		this.getNodesInfo()
	},
	methods: {
		scrolltolower(){
			setTimeout(()=>{
				this.currentIndex =3
			},80)
		},
		scrolls(e){
			let scrollTop = e.target.scrollTop
			for(let i =0;i<this.topList.length;i++){
				let h1 = this.topList[i]
				let h2 = this.topList[i+1]
				if(scrollTop>=h1&&scrollTop<h2){
					this.currentIndex = i
				}
			}
		},
		getNodesInfo(){
			const query = uni.createSelectorQuery().in(this);
			query.selectAll('.title').boundingClientRect().exec((res)=>{
				let nodes = res[0]
				let rel =[];
				nodes.map(item=>{
					rel.push(item.top)
				})
				this.topList =rel
			})
		},		
 changeactive(index){
    this.currentIndex =index
	this.doms = 'po'+index

}
}
}

三.css样式

<style lang="less">
.ld{
	display: flex;
	.left{
		width: 100px;
		border: 1px solid red;
	}
	.right{
		flex: 1;
	}
}

.active{
  background-color:#007aff ;
 }
 .titlecolor{
  background-color: red;
 }
 解析: 
 scroll-y是为了能在Y轴上进行滚动
 scroll-into-view先等于一个doms空字符串,然后给右边的每个页面自定义属性一个id,id名字就是po+index,给左边的demo一个点击事件,index也要传过去,然后就通过赋值给doms,点击哪个就对应哪个,实现锚点跳转
 scroll-with-animation是为了让他跳转的时候不僵硬,有一个动画效果
 @scroll="scrolls"是让右边滚动的时候左边的demo也对应,主要通过渲染页面完成时,在onReady中调用一个获取高度的函数,当滚动的高度在取的两个高度之间的时候,就把currentIndex赋上值
 @scrolltolower="scrolltolower"作用是,时常滚动到最后一个时候,监听就没效果,这个时候就给他一个定时器,把左边的最后一个demo的下标赋给currentIndex就可以了
  • 6
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值