1. The box with the id name testNavBar and the box with: class='{ fixedNavbar: isfixTab }'can be a containment relationship or a parallel relationship
<div id='testNavBar'></div>
<div class="container " :class='{
fixedNavbar: isfixTab }'>
</div>
or
<div id='testNavBar'>
<div :class='{
fixedNavbar: isfixTab }'>这是导航</div>
</div>
2.fixedNavbar is the class name
.fixedNavbar {
background-color: #f3f3f3;
position: fixed;
width: 100%;
z-index: 2032;
top: 0;
left: 0;
padding-bottom: 10px;
}
3.isfixTab is to control whether to add a class name
data() {
return {
isnavshow: false,
cateList:[],
cateInfo:[],
config_list:{
},
isfixTab:false
}
},
4. Monitor the page scroll event in mounted and call the handleTabFix() method
// 监听页面滚动
mounted () {
window.addEventListener('scroll', this.handleTabFix, true)
},
//离开当前组件前一定要清除滚动监听,否则进入其他路由会报错
beforeRouteLeave (to, from, next) {
window.removeEventListener('scroll', this.handleTabFix, true)
next()
},
5. Declare a method handleTabFix()
// 先分别获得id为testNavBar的元素距离顶部的距离和页面滚动的距离
// 比较他们的大小来确定是否添加fixedNavbar样式
handleTabFix() {
var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
var offsetTop = document.querySelector('#testNavBar').offsetTop
scrollTop > offsetTop ? this.isfixTab = true : this.isfixTab = false
}