先看效果图
演示.gif代码比较简单
提示:这里样式使用了less嵌套,编译报错可自行提出嵌套类
<template>
<div>
<div class="box"></div>
<scroll-view
:scroll-left="scrollleft"
id="fixd"
:class="fixtop? 'fix':''"
scroll-x="true"
style="width: 100%;white-space:nowrap;background-color:#fff; box-sizing: border-box;"
>
<div class="nav">
<div
:id="'navitem' +index"
@click="tabClick(index)"
v-for="(item,index) in nav"
:key="index"
class="nav_item"
:class="activeIndex == index? 'active':''"
>{{item}}</div>
</div>
</scroll-view>
<swiper
:style="'height:'+swiperHeight+'px'"
class="swiper"
duration="200"
:current="activeIndex"
@change="swiperChange"
>
<block v-for="(swi,s) in nav" :key="s">
<swiper-item>
<div class="content">{{swi}}</div>
</swiper-item>
</block>
</swiper>
</div>
</template>
<script>
export default {
data() {
return {
nav: [
"选项卡一",
"选项卡二",
"选项卡三",
"选项卡四",
"选项卡五",
"选项卡六",
"选项卡七",
"选项卡八"
],
fixtop: false, //是否吸顶
top: 0, //导航栏初始到屏幕顶部高度
activeIndex: 0, //选项卡及swiper位置
scrollleft: 0, //scroll-view 横向滚动条位置
windowWidth: 0, //窗口宽度
swiperHeight: 2000 //此处为swiper高度
};
},
methods: {
tabClick(e) {
this.activeIndex = e;
},
swiperChange(e) {
this.activeIndex = e.mp.detail.current;
let that = this;
const query = wx.createSelectorQuery();
query.select("#navitem" + this.activeIndex).boundingClientRect();
query.exec(function(res) {
console.log(res);
if (res[0].right > that.windowWidth) {
that.scrollleft = res[0].right;
} else if (res[0].left < 0) {
that.scrollleft = res[0].left;
}
});
}
},
onLoad() {
let that = this;
let res = wx.getSystemInfoSync();
that.windowWidth = res.windowWidth;
const query = wx.createSelectorQuery();
query.select("#fixd", ".nav").boundingClientRect();
query.exec(function(res) {
that.top = res[0].top;
});
},
onPageScroll: function(e) {
var that = this;
console.log(that.top);
if (e.scrollTop >= that.top) {
that.fixtop = true;
} else {
that.fixtop = false;
}
}
};
</script>
<style lang="less">
.box {
height: 200px;
width: 100%;
background-color: #f5f5f5;
}
.nav {
width: 100%;
display: flex;
height: 50px;
background-color: #fff;
box-sizing: border-box;
.nav_item {
flex: auto;
text-align: center;
line-height: 50px;
padding: 0 20px;
}
.active {
color: red;
}
}
.content {
background-color: #f1f1f1;
height: 2000px;
}
.fix {
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 10;
animation: move 0.2s linear;
}
@keyframes move {
from {
opacity: 0.7;
}
to {
opacity: 1;
}
}
</style>
网友评论