uni-app - - - - - 实现锚点定位和滚动监听功能(滚动监听功能暂未添加,待后续更新)

实现锚点定位和滚动监听功能

  • [1. 思路解析](#1. 思路解析)
  • [2. 代码示例](#2. 代码示例)

效果截图示例:

  • 点击左侧menu,右侧列表数据实现锚点定位

1. 思路解析

  • 点击左侧按钮,更新右侧scroll-view对应的scroll-into-view的值,即可实现右侧锚点定位
  • 滚动右侧区域,计算右侧滚动距离 动态更新左侧scroll-view对应的scroll-into-view的值,即可实现左侧锚点定位(暂无需求,先提供思路)

【scroll-view官网】

2. 代码示例

HTML

html 复制代码
<view>


	<!-- 左侧menu -->
	<scroll-view scroll-y="true" :scroll-into-view="category.categoryMenuIntoView"
		scroll-with-animation="true">
		
		<view :id='"category-menu-" + index' v-for="(item, index) in category.coffeeList" :key="item.categoryId" @click="switchCategoryMenu(item,index)">
			{{ item.categoryName }}		
		</view>
		
	</scroll-view>




	<!-- 右侧列表 -->
	<scroll-view scroll-y="true" :scroll-into-view="category.coffeeIntoView" scroll-with-animation="true">
	
		<view :id='"category-coffee-" + index' @scroll='coffeeScroll'>
			{{item.name}}
		</view>
		
	</scroll-view>

</view>

重点:

  • scroll-into-view:值应为某子元素id(id不能以数字开头)。设置哪个方向可滚动,则在哪个方向滚动到该元素
  • id设置:唯一值切不能为数字开头(后续需该值赋给scroll-into-view

JS

js 复制代码
// 定义数据
const category = reactive({
	idx: 0,
	coffeeList: [],
	categoryMenuIntoView: 'category-menu-0',
	coffeeIntoView: 'category-coffee-0'

})



/**
 * 点击切换左侧menu
 */
const switchCategoryMenu = (item, index) => {
	if (category.idx == index) return console.log('点击即为当前选中分类,无需切换逻辑')
	category.idx = index
	category.categoryMenuIntoView = `category-menu-${index}`
	category.coffeeIntoView = `category-coffee-${index}`
}



/**
 *  onLoad之后执行,预先计算出右侧锚点卡片的范围
 */
const getDistanceToTop = () => {
	distanceList.value = []; // 清空旧的距离列表
	const selectorQuery = uni.createSelectorQuery();
	selectorQuery.selectAll('.coffee-box').boundingClientRect(rects => {
		console.log('rects.map(rect => rect.top)', rects.map(rect => rect.top))
		distanceList.value = rects.map(rect => rect.top); // 直接映射为 `top` 值
	}).exec();
}



/**
 *  节流监听右侧区域滚动,联动左侧menu锚点定位
 *  根据滚动出的距离,属于getDistanceToTop对应的哪一个范围,动态修改左侧scroll-into-view的值即可
 */
const coffeeScroll = throttle((event) => {
	let scrollTop = event.detail.scrollTop;
}, 200); // 节流时间 300ms


如此即可实现锚点定位功能。(滚动监听功能后续可能会更新)

相关推荐
2501_916008893 小时前
2026 iOS 证书管理,告别钥匙串依赖,构建可复制的签名环境
android·ios·小程序·https·uni-app·iphone·webview
2501_915918419 小时前
iOS App 拿不到数据怎么办?数据解密导出到分析结构方法
android·macos·ios·小程序·uni-app·cocoa·iphone
2501_916008899 小时前
iOS App 抓包看不到内容,从有请求没数据一步步排查
android·ios·小程序·https·uni-app·iphone·webview
扶苏10029 小时前
记一次 uni-app开发微信小程序 textarea 的“伪遮挡”踩坑实录
微信小程序·小程序·uni-app
RuoyiOffice1 天前
企业请假销假系统设计实战:一张表、一套流程、两段生命周期——BPM节点驱动的表单变形术
java·spring·uni-app·vue·产品运营·ruoyi·anti-design-vue
KongHen021 天前
uniapp-x实现自定义tabbar
前端·javascript·uni-app·unix
RuoyiOffice1 天前
SpringBoot+Vue3+Uniapp实现PC+APP双端考勤打卡设计:GPS围栏/内网双模打卡、节假日方案、定时预生成——附数据结构和核心源码讲解
java·spring·小程序·uni-app·vue·产品运营·ruoyi
2501_915921431 天前
2026 iOS 上架新趋势 iOS 发布流程模块化
android·ios·小程序·https·uni-app·iphone·webview
窝子面2 天前
uni-app的初体验
uni-app
笨笨狗吞噬者2 天前
【uniapp】微信小程序实现自定义 tabBar
前端·微信小程序·uni-app