HTML
非重點的代碼,比如樣式啥的,我就不放上來了,一筆帶過
簡略的寫一下html代碼,可以對照文章最后的效果圖看,應(yīng)該不難理解
<div :style="{ paddingBottom: paddingBottom}"> <header>資源信息</header> <div> <!-- 公司信息 瀏覽量 --> </div> <div id="fixedBar" :class="{ fixedBar: isFixed }"> <!-- 品名 --> <!-- 規(guī)格 --> <!-- 產(chǎn)地 --> <!-- 單價 --> </div> <div :style="{ marginTop: marginTop }"> <!-- 數(shù)據(jù)列表 --> </div> <footer class="footer"> <button>訂閱</button> <button>關(guān)閉</button> <div v-show="advertShow"> <a @click="del">×</a> <img src="./廣告.jpg" /> </div> </footer></div><style> .fixedBar { position: fixed; top: 0; z-index: 999; width: 100%; }</style>VUE
1. data ()
data () { paddingBottom: '1.5rem', // 給最外層div一個padding-bottom // 因為footer是fixed定位 如果padding-bottom為0 數(shù)據(jù)列表拉到最下面的時候 會有部分數(shù)據(jù)被footer擋住 isFixed: false, // bar浮動 offsetTop: 0, // 觸發(fā)bar浮動的閾值 marginTop: 0, // 觸發(fā)bar浮動的同時 給數(shù)據(jù)列表一個margin-top 防止列表突然上移 會很突兀 advertShow: true, // 廣告顯示}2. mounted ()
mounted () { // 設(shè)置初始的 padding-bottom 值為 footer 的高度 +20 防止數(shù)據(jù)列表拉到最下面被footer擋住 +多少自定 this.paddingBottom = document.querySelector('.footer').offsetHeight + 20 + 'px'; // 設(shè)置bar浮動閾值為 #fixedBar 至頁面頂部的距離 this.offsetTop = document.querySelector('#fixedBar').offsetTop; // 開啟滾動監(jiān)聽 window.addEventListener('scroll', this.handleScroll);}3. methods
methods: { // 關(guān)閉廣告 del () { this.advertShow = true; this.$nextTick(() => { this.paddingBottom = document.querySelector('.footer').offsetHeight + 20 + 'px'; }); }, // 滾動監(jiān)聽 滾動觸發(fā)的效果寫在這里 handleScroll () { var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; if (scrollTop >= this.offsetTop) { this.isFixed = true; this.marginTop = document.querySelector('#fixedBar').offsetHeight + 'px'; } else { this.isFixed = false; this.marginTop = 0; } }}4. destroyed ()
destroyed () { window.removeEventListener('scroll', this.handleScroll); // 離開頁面 關(guān)閉監(jiān)聽 不然會報錯}效果圖




以上這篇VUE 實現(xiàn)滾動監(jiān)聽 導航欄置頂?shù)姆椒ň褪切【幏窒斫o大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答