欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > uni-app - - - - - 实现锚点定位和滚动监听功能(滚动监听功能暂未添加,待后续更新)

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

2025/5/3 18:00:05 来源:https://blog.csdn.net/Dark_programmer/article/details/142516122  浏览:    关键词:uni-app - - - - - 实现锚点定位和滚动监听功能(滚动监听功能暂未添加,待后续更新)

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

  • 1. 思路解析
  • 2. 代码示例

效果截图示例:

  • 点击左侧menu,右侧列表数据实现锚点定位
    在这里插入图片描述

1. 思路解析

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

【scroll-view官网】

2. 代码示例

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

// 定义数据
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 = indexcategory.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


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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词