vue吸頂效果

一直很好奇吸頂效果,今天自己來實(shí)現(xiàn)一波,話不多說,先上代碼為敬。

<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>
鼓搗一波才發(fā)現(xiàn),原來原理非常簡(jiǎn)單,只用通過一個(gè)滾動(dòng)監(jiān)聽事件,來控制樣式就搞定了,需要注意的是離開當(dāng)前組件的時(shí)候要移除滾動(dòng)事件監(jiān)聽,不然會(huì)一直報(bào)錯(cuò)。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1、通過CocoaPods安裝項(xiàng)目名稱項(xiàng)目信息 AFNetworking網(wǎng)絡(luò)請(qǐng)求組件 FMDB本地?cái)?shù)據(jù)庫(kù)組件 SD...
    陽(yáng)明AI閱讀 16,205評(píng)論 3 119
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,058評(píng)論 25 709
  • 假如有一天,你不小心將室友的電腦弄個(gè)壞了,你要怎么辦?以下是一個(gè)真實(shí)案例。 事情的經(jīng)過是這樣的:室友A在外面租了房...
    soho辭安閱讀 3,055評(píng)論 0 1
  • 文|兩根羽毛 參賽編號(hào):930 (一)海灘 你沖我招手 眉眼低垂 嘴角含笑 “來呀 小哥哥” 奔向大海的你...
    兩根羽毛閱讀 871評(píng)論 11 14
  • 端午節(jié)假期加周末共三天、前2天都在忙乎看家人朋友、第三天才自己在家、早上起來享受難得的放松、不需要趕時(shí)間、不必須穿...
    極簡(jiǎn)如蟬閱讀 214評(píng)論 0 0

友情鏈接更多精彩內(nèi)容