監聽頁面滾動
在methods中定義一個方法
handleScroll
() {
//獲取滾動時的高度 let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; let oneHeight = this.$refs.scrollOne.offsetHeight ; let twoHeight = this.$refs.scrollTwo.offsetHeight + oneHeight; let threeHeight = this.$refs.scrollThree.offsetHeight + twoHeight; // // console.log(scrollTop) if (scrollTop > 0) { //滾動大於0的時候要做的操作 } if (scrollTop > 200) { //大於200的時候要做的操作 } if (scrollTop > oneHeight) { //這是滑動到scrollTwo的距離要做的操作
} if (scrollTop > twoHeight) { //這是滑動到scrollThree要做的操作 }
html中
<div class="gooddetail-info"> <div ref="scrollOne"></div> <div ref="scrollTwo"></div> <div ref="scrollThree"></div> </div>
在mounted監聽
mounted() { window.addEventListener("scroll",this.handleScroll);
},
最后要銷毀這個監聽要不然會在其他的頁面中 執行 報錯
destroyed() { document.removeEventListener('scroll', this.handleScroll) }