uniapp定位滑动到多层嵌套item如何实现

在uniapp中,如何实现页面滑动时定位到多层嵌套的item?比如一个列表里包含多个分类,每个分类下又有子项,当滚动页面时,需要根据滚动位置自动高亮显示对应的分类标题。尝试过使用scroll-view和uni.createSelectorQuery()获取节点信息,但嵌套层级较深时无法准确匹配。请问有没有成熟的解决方案或示例代码?

2 回复

使用scroll-into-view属性,绑定目标元素的id。在嵌套结构中,确保目标item有唯一id,通过计算目标位置并设置scroll-into-view的值即可实现定位滚动。


在UniApp中,实现定位滑动到多层嵌套的item,可以通过以下步骤实现:

  1. 获取目标元素位置:使用uni.createSelectorQuery()获取目标DOM元素的位置信息。
  2. 计算滚动位置:根据嵌套结构计算需要滚动的具体位置。
  3. 执行滚动:使用uni.pageScrollTo()或scroll-view组件的scrollTop属性实现滚动。

示例代码(基于scroll-view):

<template>
  <view>
    <scroll-view scroll-y :scroll-top="scrollTop" @scroll="onScroll">
      <!-- 多层嵌套结构 -->
      <view v-for="section in list" :key="section.id">
        <view class="section-title">{{ section.title }}</view>
        <view v-for="item in section.items" :key="item.id" :id="'item-' + item.id">
          {{ item.name }}
        </view>
      </view>
    </scroll-view>
    <button @click="scrollToItem">滚动到指定项</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      scrollTop: 0,
      list: [
        {
          id: 1,
          title: "Section 1",
          items: [
            { id: 101, name: "Item 1-1" },
            { id: 102, name: "Item 1-2" }
          ]
        },
        {
          id: 2,
          title: "Section 2",
          items: [
            { id: 201, name: "Item 2-1" },
            { id: 202, name: "Item 2-2" }
          ]
        }
      ]
    };
  },
  methods: {
    scrollToItem() {
      const itemId = "item-202"; // 目标项ID
      const query = uni.createSelectorQuery().in(this);
      query.select(`#${itemId}`).boundingClientRect();
      query.select(".scroll-view").boundingClientRect();
      query.exec((res) => {
        if (res[0] && res[1]) {
          // 计算相对于scroll-view的滚动位置
          this.scrollTop = res[0].top - res[1].top + this.scrollTop;
        }
      });
    },
    onScroll(e) {
      this.scrollTop = e.detail.scrollTop;
    }
  }
};
</script>

关键点:

  • scroll-view:必须使用scroll-view组件并设置scroll-y
  • scrollTop:通过动态绑定scrollTop控制滚动位置。
  • 元素查询:使用createSelectorQuery获取目标元素和滚动容器的位置。
  • 位置计算:通过boundingClientRect计算相对位置。

如果使用页面滚动(非scroll-view),将uni.pageScrollTogetScrollOffset结合,但注意H5端兼容性。

回到顶部