一直很好奇吸顶效果,今天自己来实现一波,话不多说,先上代码为敬。
<template>
<div class="content">
<div class="green">green</div>
<div class="yellow" :class="{fixed:fixed}">yellow</div>
<div class="yellow_green"></div>
</div>
</template>
<script>
export default {
data(){
return{
fixed:false
}
},
mounted(){
window.addEventListener('scroll',this.handleScroll)
},
methods:{
handleScroll(){
let scrollTop=window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
let offsetTop=document.querySelector('.yellow').offsetTop;
if(scrollTop>offsetTop){
this.fixed=true;
}else{
this.fixed=false;
}
}
},
destroyed(){
window.removeEventListener('scroll',this.handleScroll)
}
}
</script>
<style lang="less" scoped>
.content{
position: relative;
div{
width: 750px;
height: 500px;
text-align: center;
background: gray;
}
.green{
background: green;
}
.yellow{
background: yellow;
height: 100px;
}
.yellow_green{
background: greenyellow;
height: 2000px;
}
.fixed{
position: fixed;
top: 0;
left: 0;
}
}
</style>