vue - vue中实现移动端顶部菜单栏吸顶功能
vue中实现移动端顶部菜单栏吸顶功能
·
vue中实现移动端顶部菜单栏吸顶功能:
需要实现的是当第二张当内容滑动到顶部的时候,需要吸附上去并改变背景颜色;
思路:
1,监听页面的滚动条;
2,当滚动的高度大于海报图的高度时;需要使用固定定位 吸附到页面的顶端(需要有一个过渡的效果,不能太生硬)
3,当吸顶时要动态的改变类名,以此来改变背景颜色和高亮显示;
vue中实现:
<template>
<div class="tab">
<div class="container" ref="nav" :class="{ sticky: isSticky }">
<div
class="tab-item"
v-for="(item, index) in tabList"
:key="index"
:class="{ active: act_index === index }"
>
<span class="text">{{ item.itemName }}</span>
</div>
</div>
<div class="content">
内容区
</div>
</div>
</template>
<script>
export default {
data() {
return {
isSticky: false, //是否吸顶
navHeight: 0, // nav的高度
conScrollTop: 0, // 容器滚动条距离顶部高度
thatOffsetTop: 0, // 当前组件距离顶部高度
// tab列表
tabList: [
{
compName: "overviewPart",
itemName: "业务总况",
},
{
compName: "totalTrend",
itemName: "总况趋势",
},
{
compName: "organizationTrend",
itemName: "机构趋势",
},
{
// compName: 'organizationDetails',
itemName: "机构详情",
},
{
// compName: 'nowReport',
itemName: "当日战报",
},
{
// compName: 'financePart',
itemName: "财务板块 ",
},
{
// compName: 'marketPart',
itemName: "市场板块",
},
{
// compName: 'operatePart',
itemName: "运营板块",
},
],
};
},
mounted() {
this.initSticky();
},
methods: {
initSticky() {
this.navHeight = this.$refs.nav.clientHeight; //导航栏的高度
console.log(" this.navHeight :",this.navHeight );
window.addEventListener("scroll", (e) => {
this.thatOffsetTop = this.getScrollTop(); // 滚动条距离顶部高度
// 当滚动条距顶部的高度 大于 等于 banner的高度 就吸顶
if (this.thatOffsetTop >= this.navHeight) {
this.isSticky = true;
} else {
this.isSticky = false;
}
});
},
// 滚动条距离顶部高度
getScrollTop() {
var scrollTop = 0;
if (document.documentElement && document.documentElement.scrollTop) {
scrollTop = document.documentElement.scrollTop;
} else if (document.body) {
scrollTop = document.body.scrollTop;
}
return scrollTop;
},
},
};
</script>
<style scoped lang="scss">
.content{
height: 1000px;
background-color: aquamarine;
}
.tab {
height: 100%;
width: 100%;
}
.container {
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap; /*允许换行*/
}
.tab-item {
text-align: center;
width: 25%;
height: 35px;
line-height: 35px;
border-right: 1px solid #ccc;
border-bottom: 1px solid #ccc;
font-size: 14px;
}
// 是否吸顶
.sticky {
position: fixed;
width: 100%;
transition: color 0.2s linear;
transition: background 0.2s linear;
background: #1e9cfe;
color: #ffff;
top: 0;
z-index: 99999999;
.active {
transition: color 0.2s linear;
color: #fff;
span {
border-bottom: 2px solid #ffffff;
}
}
}
// 选中的高亮
.active {
color: #1a9cfe;
span {
border-bottom: 2px solid #4fadff;
}
}
</style>
更多推荐
已为社区贡献16条内容
所有评论(0)