有时候我们在vue项目中需要用到有关scroll的动画,但是又没jquery那样的animate简单的动画方法,又要避免引入jquery的包导致过大,于是就用原生js模仿一个:(可用于返回顶部,锚点动画等)

selector此参数为id名,可直接调用该点击事件

goAnchor(selector) {
      let anchor = this.$el.querySelector(selector);
      let total = anchor.offsetTop;
      let distance = document.documentElement.scrollTop || document.body.scrollTop;
      let step = total / 50;
      if (total > distance) {
        smoothDown();
      } else {
        let newTotal = distance - total;
        step = newTotal / 50;
        smoothUp();
      }
      function smoothDown() {
        if (distance < total) {
          distance += step;
          document.body.scrollTop = distance;
          document.documentElement.scrollTop = distance;
          setTimeout(smoothDown, 10);//自定义时间
        } else {
          document.body.scrollTop = total;
          document.documentElement.scrollTop = total;
        }
      }
      function smoothUp() {
        if (distance > total) {
          distance -= step;
          document.body.scrollTop = distance;
          document.documentElement.scrollTop = distance;
          setTimeout(smoothUp, 10);
        } else {
          document.body.scrollTop = total;
          document.documentElement.scrollTop = total;
        }
      }
    }

 

Logo

前往低代码交流专区

更多推荐