非重點的代碼,比如樣式啥的,我就不放上來了,一筆帶過
簡略的寫一下
1. data ()
data () {
paddingBottom: '1.5rem', // 給最外層div一個padding-bottom
// 因為footer是fixed定位 如果padding-bottom為0 數據列表拉到最下面的時候 會有部分數據被footer擋住
isFixed: false, // bar浮動
offsetTop: 0, // 觸發bar浮動的閾值
marginTop: 0, // 觸發bar浮動的同時 給數據列表一個margin-top 防止列表突然上移 會很突兀
advertShow: true, // 廣告顯示
}
2. mounted ()
mounted () {
// 設置初始的 padding-bottom 值為 footer 的高度 +20 防止數據列表拉到最下面被footer擋住 +多少自定
this.paddingBottom = document.querySelector('.footer').offsetHeight + 20 + 'px';
// 設置bar浮動閾值為 #fixedBar 至頁面頂部的距離
this.offsetTop = document.querySelector('#fixedBar').offsetTop;
// 開啟滾動監聽
window.addEventListener('scroll', this.handleScroll);
}
3. methods
methods: {
// 關閉廣告
del () {
this.advertShow = true;
this.$nextTick(() => {
this.paddingBottom = document.querySelector('.footer').offsetHeight + 20 + 'px';
});
},
// 滾動監聽 滾動觸發的效果寫在這里
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); // 離開頁面 關閉監聽 不然會報錯
}
效果圖
以上這篇開發者。