美文网首页
vue吸顶效果

vue吸顶效果

作者: RDbaby | 来源:发表于2018-07-16 11:31 被阅读0次

一直很好奇吸顶效果,今天自己来实现一波,话不多说,先上代码为敬。

<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>
鼓捣一波才发现,原来原理非常简单,只用通过一个滚动监听事件,来控制样式就搞定了,需要注意的是离开当前组件的时候要移除滚动事件监听,不然会一直报错。

相关文章

网友评论

      本文标题:vue吸顶效果

      本文链接:https://www.haomeiwen.com/subject/ozswjftx.html