vue监听滚动事件实现顶部元素header渐隐渐显效果,滚到一定距离固定在顶部,绑定全局事件后,离开页面需要移除这个监听的事件
html
<template>
<div>
<router-link tag="div" to="/" class="header-sbs" v-show="showAbs">
<span class="iconfont header-abs-back"></span>
</router-link>
<div class="header-fixed" v-show="!showAbs" :style="opacityStyle">
<router-link to="/" class="">
<span class="iconfont header-fixed-back"></span>
</router-link>
景点详情
</div>
</div>
</template>
css
<style lang="less" scoped>
.header-sbs{
position: absolute;
left:.2rem;
top:.2rem;
width: .8rem;
height:.8rem;
line-height: .8rem;
text-align: center;
border-radius: .4rem;
background: rgba(0,0,0,.8);
.header-abs-back{
color:#fff;
font-size: .4rem;
}
}
.header-fixed{
z-index: 10;
position: fixed;
top: 0;
left:0;
right:0;
bottom:0;
/*overflow: hidden;*/
text-align: center;
color:#fff;
height: .86rem;
line-height: .8rem;
background: #25a4bb;
font-size: 0.32rem;
.header-fixed-back{
position: absolute;
top:0;
left: 0;
width:.64rem;
font-size: .4rem;
text-align: center;
color:#ffffff;
}
}
</style>
js
<script>
export default {
name: "DetailHeader",
data(){
return{
showAbs:true,
opacityStyle:{
opacity:0
}
}
},
methods:{
handleScroll(){
const top = document.documentElement.scrollTop;
console.log(top);
if(top > 60){
let opacity = top / 140;
opacity = opacity > 1 ? 1:opacity;
this.opacityStyle = {opacity};
this.showAbs = false
}else{
this.showAbs = true
}
}
},
mounted (){
window.addEventListener('scroll',this.handleScroll)
},
// 离开该页面需要移除这个监听的事件
destroyed(){
window.removeEventListener('scroll',this.handleScroll)
}
}
</script>
页面滚下滚动的效果