uniapp仿淘宝详情页页面滑动tab切换
建立util文件夹放一个Tool.js:
export default{
getRect(selector){
return new Promise((resolve) => {
// uni.createSelectorQuery获取元素节点,小程序里wx.createSelectorQuery Vue里在元素上添加ref属性,使用$refs来获取到该元素
let view = uni.createSelectorQuery().select(selector);
view.fields({
size: true,
rect: true,
scrollOffset:true
}, (res) => {
resolve(res);
}).exec();
})
}
}
把Tool.js在main.js中引入:
//获取页面元素大小和位置
import Tool from './util/Tool.js'
Vue.prototype.$Tool = Tool
index.vue中:
<template>
<view>
<view class="topSel">
<view class="nav" v-show="isShowTile">
<view v-for="(item,navIndex) in nav" :key="navIndex" class="navList" :class="currentNav==navIndex? 'ac':''" @tap="selNav(navIndex)">{{item}}</view>
</view>
</view>
<view class="Vue1">Vue1</view>
<view class="Vue2">Vue2</view>
<view class="Vue3">Vue3</view>
</view>
</template>
<!-- 此代码为测试~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-->
<script>
export default {
data() {
return {
nav: ["Vue1", "Vue2", "Vue3"],
currentNav: 0,
HtmlTop:0,
JavascriptTop:0,
CssTop:0,
oldHeight: uni.upx2px(550),
isShowTile:false
};
},
onShow(){
},
// 获取每个标签的top值
mounted() {
this.$Tool.getRect(".Vue1").then(res => {
this.HtmlTop = res.top
})
this.$Tool.getRect(".Vue2").then(res => {
this.CssTop = res.top
})
this.$Tool.getRect(".Vue3").then(res => {
this.JavascriptTop = res.top
})
},
// 监听页面滚动,同时控制顶部tab现隐
onPageScroll(e){
if(e.scrollTop>=this.JavascriptTop){
this.$set(this,'currentNav',2)
}else if(e.scrollTop>=this.CssTop){
this.$set(this,'currentNav',1)
}else{
this.$set(this,'currentNav',0)
}
if(this.oldHeight<e.scrollTop){
this.isShowTile = true
}else{
this.isShowTile = false
}
},
methods: {
// 点击tab滚动到对应位置
selNav(index) {
this.currentNav = index
switch (index) {
case 0:
uni.pageScrollTo({
scrollTop: this.HtmlTop
})
break;
case 1:
uni.pageScrollTo({
scrollTop: this.CssTop
})
break;
case 2:
uni.pageScrollTo({
scrollTop: this.JavascriptTop
})
break;
}
}
}
};
</script>
<style lang="scss">
page {
// padding-top: 100rpx;
}
.topSel {
width: 100%;
// height: 100rpx;
background-color: rgba(255,255,255,.2);
.nav {
background-color: black;
position: fixed;
top: 50px;
display: flex;
opacity: 1;
align-items: center;
justify-content: space-between;
width: 100%;
margin: 0 auto;
font-size: 31rpx;
color: #666;
// line-height: 60rpx;
.ac {
border-bottom: 2px transparent solid;
border-image: linear-gradient(to right, #ffb759, #ff3251) 1 10;
color: #ff3251;
line-height: 70rpx;
}
}
}
.Vue1{
width: 750rpx;
height: 2000rpx;
background-color: #1CBBB4;
color: #fff;
}
.Vue3 {
width: 750rpx;
height: 2000rpx;
background-color: pink;
color: #fff;
}
.Vue2{
width: 750rpx;
height: 2000rpx;
background-color: #00BFFF;
color: #fff;
}
</style>