天天看點

工作-頁面滑動到一定高度吸頂

背景

在頁面中間有一個固定的tab欄,當頁面滑動到tab欄到達頁面頂部的時候,tab欄吸頂。點選tab頁面滑動到指定元素的位置。

代碼

<div class="tab">
      <div
        ref="serviceTab"
        :class="serviceTabActive ? 'tab_title tab_after' : 'tab_title'"
        @click="goToServiceTab"
      >
        服務
      </div>
      <div
        ref="rateTab"
        :class="ratesTabActive ? 'tab_title tab_after' : 'tab_title'"
        @click="goToRateTab"
      >
        進度
      </div>
      <div
        ref="evaluateTab"
        :class="evaluateTabActive ? 'tab_title tab_after' : 'tab_title'"
        @click="goToEvaluate"
      >
        獎勵
      </div>
      <div
        ref="questionTab"
        :class="questionTabActive ? 'tab_title tab_after' : 'tab_title'"
        @click="goToQuestion"
      >
        問題
      </div>
    </div>
           
實作思路
  • 通過監聽元素滾動事件,當到達一定高度時元素active狀态。
  • 元素的類名通過監聽滑動來修改。
  • 點選的元素的時候,頁面滾動到元素的高度。
// 在created中添加監聽事件
window.addEventListener('scroll',this.handleScroll, true);
           
PS:不要忘了在destoryed移除監聽事件哦,否則在哪個頁面都會監聽哒~
handleScroll() {
        const serviceTop = this.$refs.service.getBoundingClientRect().top;
        const ratesTop = this.$refs.rates.getBoundingClientRect().top;
        const evaluateTop = this.$refs.evaluate.getBoundingClientRect().top;
        const questionTop = this.$refs.question.getBoundingClientRect().top;

        (serviceTop <= 500 && serviceTop >-20)
          ? this.serviceTabActive = true
          : this.serviceTabActive = false;

        (ratesTop <= 127 && ratesTop > -20)
          ? this.ratesTabActive = true
          : this.ratesTabActive = false;

        (evaluateTop <= 100 && evaluateTop > -20)
          ? this.evaluateTabActive = true
          : this.evaluateTabActive = false;

        questionTop <= 300
          ? this.questionTabActive = true
          : this.questionTabActive = false;
      },
           
點選事件
// 這裡拿一個舉例,其他跟這個是一樣哒
	goToServiceTab() {
        this.serviceTabActive = true;
        // 這裡區分是因為安卓機用document.documentElement會失效
        if (/android/.test(navigator.userAgent.toLowerCase())) {
          document.body.scrollTop = this.$refs.service.offsetTop-40;
        } else {
          document.documentElement.scrollTop = this.$refs.service.offsetTop-40;
        }
      },
           

注意的小點~

  • 當滾動的元素設定了overflow-y:auto的時候,document.body.scrollTop會失效哦~
  • 安卓機document.documentElement.scrollTop也會失效哦~

繼續閱讀