微信小程序中使用 wx.pageScrollTo();進行頁面錨點定位,一定要將根目錄設置為滑動的根據(jù)。
也就是 page 要設置樣式為 overflow-y: auto;指定他的高度。
在其中,設置一個容器 home 設置id。
在添加一個內容容器 container 設置類名。
設置多個錨點,添加錨點類型 如: node0, node1, node2 等。
然后通過點擊事件傳遞要跳轉的錨點信息。
通過wx.createSelectorQuery().select(類名).boundingClientRect(res => {}),, 獲取錨點中的數(shù)據(jù)。
在通過wx.createSelectorQuery().select(“#home”).boundingClientRect(res => {}), 獲取設置的跟錨點home。
在這里不能直接獲取跟元素 page ,只能獲取當前組件的根元素,也就是home。
在通過wx.pageScrollTo({ selector: “.container”, scrollTop: 滑動的距離 });就可以滑動到錨點。
上代碼: (通過 vue3.0 + ts + vite 創(chuàng)建的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();
});