添加滚动监听事件:
mounted () {
window.addEventListener('scroll', this.handleScroll)
},
页面销毁需要取消监听:
destroyed(){
window.removeEventListener('scroll', this.handleScroll)
}
使用:
<template>
<div class="hello">
<div style="height:800px;border:1px solid blue;"></div>
<div class="nav" :class="navStatus">
<ul>
<li>导航1</li>
<li>导航2</li>
<li>导航3</li>
<li>导航4</li>
<li>导航5</li>
</ul>
</div>
<div style="height:800px;border:1px solid red;"></div>
<div style="height:800px;border:1px solid blue;"></div>
<div style="height:800px;border:1px solid red;"></div>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
navStatus:''
}
},
mounted:function (){
window.addEventListener('scroll', this.handleScroll)
},
methods: {
handleScroll(){
var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
var offsetTop = document.querySelector('.nav').offsetTop;
console.info(scrollTop,offsetTop)
if(scrollTop>=800){
this.navStatus='fixed'
}else{
this.navStatus=''
}
},
},
destroyed(){
window.removeEventListener('scroll', this.handleScroll)
}
}
</script>
<style scoped lang="scss">
.nav{
background: #000;
ul li{
float: left;
width: 100px;
color: #fff;
}
&.fixed{
position:fixed;
top: 0px;
}
}
</style>