Vue监听滚动事件响应索引及滚动距离锚点的控制

本文主要介绍vue当前页面滚动时,索引的自动切换及滚动距离锚点的控制。同时也解决了vue切换路由后上一个页面监听scroll滚动事件会在新页面报错问题。

一、直接上逻辑代码,DOM页面和样式不在一一赘述。

var doTop,  // 距离顶部的距离
  noScroll = false;  // 是否在滚动的判断
  
  mounted() {
    this.$nextTick(() => {
      this.init();
    });
  },
  destroyed() {
    window.removeEventListener("scroll", this.scroll); //注销监听页面滚动事件
  },
  methods: {
    init() {
      window.addEventListener("scroll", this.scroll); //启动监听页面滚动事件
    },
    scroll() {
      if (!noScroll) {
        var appealDo = this.getOffsetTop("appealDo") - 80; //此处的appealDo需要dom节点设置 ref="appealDo" 80为安全距离
        var appealComm = this.getOffsetTop("appealComm") - 80; //此处的appealDo需要dom节点设置 ref="appealComm"
        var scrollTop = this.getScrollTop();
        if (scrollTop <= appealDo) {
          this.activeIdx = 0;
        } else if (scrollTop > appealDo && scrollTop <= appealComm) {
          this.activeIdx = 1;
        } else if (scrollTop > appealComm) {
          this.activeIdx = 2;
        }
      }
      setTimeout(() => { // 延迟防止IOS会出现bug
        noScroll = false;
      }, 300);
    },
    toggleTypes(idx) { // 索引切换事件,通过索引控制锚点
      noScroll = true; 
      if (this.activeIdx != idx) {
        if (idx === 0) {
          this.scrollTo(0);
        } else if (idx === 1) {
          this.$nextTick(() => {
            doTop = this.getOffsetTop("appealDo") - 80;
            this.scrollTo(doTop);
          });
        } else {
          this.$nextTick(() => {
            doTop = this.getOffsetTop("appealComm") - 80;
            this.scrollTo(doTop);
          });
        }
        this.activeIdx = idx;
      }
    },
    scrollTo(val) {
      // Chrome
      document.body.scrollTop = val;
      // Firefox
      document.documentElement.scrollTop = val;
      // Safari
      window.pageYOffset = val;
    },
    getOffsetTop(obj) {
      return this.$refs[obj].offsetTop;
    },
    getScrollTop() {
      return document.documentElement.scrollTop || document.body.scrollTop;
    }
}

你可能感兴趣的:(VUE,Vue2.0从零到一)