天天看点

工作-页面滑动到一定高度吸顶

背景

在页面中间有一个固定的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也会失效哦~

继续阅读