类似京东商品详情-点击顶部详情跳转到页面对应的详情区域,点击评价跳转到页面对应的评价区域等。
照例,先封装方法:
封装方法
util.js
/**
* 锚点跳转(如:商品详情页面跳转)
* @param {string} targetId 目标id
* @param {string} rootId 外层盒子根id
*/
export const goByAnchor = (targetId, rootId) => {
if (targetId) {
uni.createSelectorQuery()
.select('#' + targetId)
.boundingClientRect(data => {
// 目标位置节点 类或者 id
uni.createSelectorQuery()
.select("#" + rootId)
.boundingClientRect(res => {
// 最外层盒子节点类或者 id
uni.pageScrollTo({
duration: 300, // 过渡时间
scrollTop: data.top - res.top - 88, // 到达距离顶部的top值
})
})
.exec()
})
.exec();
} else {
uni.pageScrollTo({
scrollTop: 0,
duration: 300
});
}
}
/**
* 获取当前元素的一些info,如:距离顶部的距离
*/
export const getElementInfoById = (elementId) => {
return new Promise((resolve) => {
uni.createSelectorQuery()
.select('#' + elementId)
.boundingClientRect(data => {
resolve(data)
})
.exec()
})
}
页面调用
<view class="goods-detail" id="goods-detail">
<!-- 顶部导航 -->
<uni-nav-bar left-icon="back" fixed statusBar :border="false" :backgroundColor="navBg" class="custom-nav" @clickLeft="pageBack">
<template v-if="navBg == '#fff'">
<view class="nav-title flex-around-center">
<text :class="{ 'active-nav-title': !navTab }" @click="handleAnchor()">宝贝</text>
<text :class="{ 'active-nav-title': navTab == 'goodsStand' }" @click="handleAnchor('goodsStand')">规格</text>
<text :class="{ 'active-nav-title': navTab == 'goodsEvaluation' }" @click="handleAnchor('goodsEvaluation')">评价</text>
<text :class="{ 'active-nav-title': navTab == 'goodsDetail' }" @click="handleAnchor('goodsDetail')">商品详情</text>
</view>
</template>
</uni-nav-bar>
<!-- 其他内容 -->
<!-- 规格 -->
<view class="goods-stand" id="goodsStand">
<!-- 内容 -->
</view>
<!-- 评价 -->
<view class="goods-evaluation" id="goodsEvaluation">
<!-- 内容 -->
</view>
<!-- 商品详情 -->
<view class="img-list" id="goodsDetail">
<!-- 内容 -->
</view>
</view>
data() {
return {
navBg: 'rgba(0, 0, 0, .05)', // 顶部导航栏的背景色
navTab: '', // 顶部导航的tab标识
}
},
// 这里通过页面生命周期监听滚动条的位置,对应的回显高亮tab
onPageScroll(e) {
if (e.scrollTop > 0) {
this.navBg = '#fff'
getElementInfoById('goodsStand').then((res) => {
if (res.top < 88) {
this.navTab = 'goodsStand'
}
})
getElementInfoById('goodsEvaluation').then((res) => {
if (res.top < 88) {
this.navTab = 'goodsEvaluation'
}
})
getElementInfoById('goodsDetail').then((res) => {
if (res.top < 88) {
this.navTab = 'goodsDetail'
}
})
} else {
this.navTab = ''
this.navBg = 'rgba(0, 0, 0, .05)'
}
},
methods: {
// 锚点跳转
handleAnchor(type) {
this.navTab = type
goByAnchor(type, 'goods-detail')
},
}