1. 程式人生 > >如何在Vue專案中實現吸頂元素

如何在Vue專案中實現吸頂元素

我的思路就是判斷合適的時候將這個元素的position設為fixed,那麼這個合適的時機如何判斷呢?我們可以計算頁面滾動的距離。

監聽頁面滾動狀態

mounted鉤子中加入以下程式碼:

mounted() {
  // handleScroll為頁面滾動的監聽回撥
  window.addEventListener('scroll', this.handleScroll);
 },

離開頁面時要移除監聽,在destroyed鉤子中移除監聽:

destroyed(){
  window.removeEventListener('scroll', this.handleScroll);
},

計算吸頂元素到頁面頂部的距離

// 監聽dom渲染完成
this.$nextTick(function(){
  // 這裡fixedHeaderRoot是吸頂元素的ID
  let header = document.getElementById("fixedHeaderRoot");
  // 這裡要得到top的距離和元素自身的高度
  this.offsetTop = header.offsetTop;
  this.offsetHeight = header.offsetHeight;
  console.log("offsetTop:" + this.offsetTop + "," + this.offsetHeight);
});

判斷頁面滾動距離

handleScroll(){
  // 得到頁面滾動的距離
  let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
  // 判斷頁面滾動的距離是否大於吸頂元素的位置
  this.headerFixed = scrollTop > (this.offsetTop - this.offsetHeight);
},

得到一個boolean值的headerFixed,然後就可以動態設定樣式了。

.isFixed{
  position: fixed;
  top: px2rem(110);
  left: px2rem(20);
  right: px2rem(20);
}

在DOM中:

<div id="fixedHeaderRoot">
  <div id="knowPointHeader" class="knowPointHeader" :class="headerFixed?'isFixed':''">
    <div><span>知識模組</span></div>
    <div><span>知識點</span></div>
    <div><span>能力要求</span></div>
  </div>
</div>