1.頂吸
需求:某個元素要在滾動列表的時候吸住頂部
mounted() {
window.addEventListener("scroll", this.suckTopFunc);
},
beforeDestroy() {
window.removeEventListener("scroll", this.suckTopFunc);
},
methods:{
suckTopFunc() {
let offsetTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop;
//offsetTop是滾動條到頂部的距離
if (offsetTop >= 110) {
//在這里做操作
} else {
//在這里做操作
}
}
}
2.吸底
需求:有個列表,但是底部需要自己加總計數據的div,并且始終處在底部
思路:通過標識元素判斷,視口是否顯示到了列表的最下方,
如果顯示到了,則總計的盒子按照正常文檔流顯示,
如果沒有顯示,則總計的盒子position:fixed到頁面底部
<ul>
<li>1</li>
<li>1</li>
<li>1</li>
<li>1</li>
<li>1</li>
......
</ul>
// 這里可以加個標識用的元素,用來判斷頁面是否滾動到列表最下方
<div class="tips" ref="tips"></div>
<div :class="isFixed ? 'fixed-style' : ''">
總計:5
</div>
data () {
return {
isFixed: false
}
},
beforeDestroy() {
window.removeEventListener("scroll", this.handlerScroll);
},
mounted(){
this.$nextTick(() => {
window.addEventListener("scroll", this.handlerScroll);
});
},
methods:{
handlerScroll() {
//在這傳入標識元素的節點,用$refs獲取
this.isFixed = this.isElementNotInViewport(this.$refs.tips) ? true : false;
},
// 在這判斷,總計的div是否顯示在頁面中
isElementNotInViewport (el) {
let rect = el.getBoundingClientRect();
return (
rect.top >= (window.innerHeight || document.documentElement.clientHeight) ||
rect.bottom <= 0
);
};
}