隐藏

微信小程序设置锚点定位,wx.pageScrollTo

发布:2023/7/3 14:47:40作者:管理员 来源:本站 浏览次数:306

   微信小程序中使用 wx.pageScrollTo({)};进行页面锚点定位,一定要将根目录设置为滑动的根据。


       也就是 page 要设置样式为 overflow-y: auto;指定他的高度。

       在其中,设置一个容器 home 设置id。

       在添加一个内容容器 container 设置类名。

       设置多个锚点,添加锚点类型 如: node0, node1, node2 等。

       然后通过点击事件传递要跳转的锚点信息。


       通过wx.createSelectorQuery().select(类名).boundingClientRect(res => {}),, 获取锚点中的数据。

       在通过wx.createSelectorQuery().select(“#home”).boundingClientRect(res => {}), 获取设置的跟锚点home。

       在这里不能直接获取跟元素 page ,只能获取当前组件的根元素,也就是home。

       在通过wx.pageScrollTo({ selector: “.container”, scrollTop: 滑动的距离 });就可以滑动到锚点。


看不懂的看代码, (通过 vue3.0 + ts + vite 创建的uni-app 项目)


page {

width: 100%;

   height: 100vh;

   display: block;

   overflow-y: auto;  /* 重点 */

   overflow-x: hidden;

   box-sizing: border-box;

}


 


<view id="home">

<view class="container">

<!-- 内容 锚点点击事件 -->

<view v-for="(item, index) in data" :key="index" @click="jump(item, index)"></view>

<!-- 锚点 -->

<view class="node0"></view>

<view class="node1"></view>

<view class="node2"></view>

</view>

</view>


 


let data = ["1","2","3","4"],


const jump = (row: any, index: number): void => {

let className = String('.node' + index);

   uni.createSelectorQuery().select(className).boundingClientRect((con: any) => { // 获取点击要跳转的锚点信息

       uni.createSelectorQuery().select("#home").boundingClientRect((res: any) => { // 获取根元素要滑动的元素

           uni.pageScrollTo({

               selector: "#home",  // 滑动的元素

               // duration: 1500, //过渡时间

               scrollTop: con.top - res.top, //到达距离顶部的top值

           });

       }).exec();

   }).exec();

});