醬醬,好久不見鴨!
前言:吸頂效果圖:
1、滾動(dòng)前:

image.png
2、滾動(dòng)中:

image.png
3、滾動(dòng)超過后:

image.png
直觀效果可參pc端微博左側(cè)的信息欄
第一步:html 中:
在你要實(shí)現(xiàn)吸頂效果的div上,加上如下這一行代碼:

image.png
下方代碼自取↓
:class="{'is_fixed' : isFixed}"
觸發(fā)吸頂效果的位置,如下:

image.png
下方代碼自取↓
<div id="boxFixed"></div>
第二步:data 定義中:

image.png
下方代碼自取↓
data() {
return {
isFixed: false,
offsetTop: 0,
}
}
第三步:在 mounted 與 destroyed 中
mounted() {
window.addEventListener('scroll', this.initHeight);
this.$nextTick(() => {
//獲取對(duì)象相對(duì)于版面或由 offsetTop 屬性指定的父坐標(biāo)的計(jì)算頂端位置
this.offsetTop = document.querySelector('#boxFixed').offsetTop;
})
},
//回調(diào)中移除監(jiān)聽
destroyed() {
window.removeEventListener('scroll', this.handleScroll)
},
第四步:在 methods 方法定義中:
/********* start-目錄吸頂********/
initHeight() {
// 設(shè)置或獲取位于對(duì)象最頂端和窗口中可見內(nèi)容的最頂端之間的距離 (被卷曲的高度)
var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
//如果被卷曲的高度大于吸頂元素到頂端位置 的距離
this.isFixed = scrollTop > this.offsetTop ? true : false;
},
/********* end-目錄吸頂********/
最后一步:在css中:
.is_fixed{
width: 100%;
position: fixed;
top: 0;
z-index: 999;
}
大功告成,感謝博文:
http://m.itdecent.cn/p/5fc421a2f12a