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


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

相关推荐
不如摸鱼去1 天前
Wot UI 2.3.0 发布:二维码组件来了,Open Wot 与 wot-starter 同步更新
前端·ui·微信小程序·前端框架·uni-app
anyup1 天前
uni-app 没有根组件?仅需几行代码实现全局 Toast 和 Modal
前端·架构·uni-app
2501_916007471 天前
Python实现HTTPS爬虫的完整指南:使用requests、BeautifulSoup、Selenium和Scrapy
爬虫·python·ios·小程序·https·uni-app·iphone
AI_AGENT_DEV_AI1 天前
原生 APP(iOS / Android)的开发与上线
uni-app
小徐_23332 天前
Wot UI 2.3.0 发布:二维码组件来了,Open Wot 与 wot-starter 同步更新
前端·微信小程序·uni-app
skiyee2 天前
🔥 oiyo & unibest = 又新又好的 uniapp 模板
前端·uni-app
结网的兔子4 天前
【前端开发】Web端迁移至 uni-app 及鸿蒙扩展方案对比
前端·uni-app·harmonyos
2501_915909064 天前
iOS 应用反调试技详解术 检测调试器的原理与防护实践
android·ios·小程序·https·uni-app·iphone·webview
AI多Agent协作实战派4 天前
AI多Agent协作系统实战(二十八):顶栏统一战争——从1个页面异常到31个页面全量对齐
数据库·人工智能·uni-app
00后程序员张4 天前
iOS加固技术路线全面解析:Bitcode模式、源码模式与汇编模式对比及爱加密优势
android·汇编·ios·小程序·uni-app·cocoa·iphone