vue js 获取滚动距离 以及 返回顶部按钮

vue js 获取滚动距离 以及 返回顶部按钮_第1张图片

  1. 获取滚动距离 判断是否回到顶部
  data() {
     
    return {
     
      scrollNum: 0, //滚动距离
      isTop: false, //是否显示回到顶部按钮
      myTimer: -1, //防止点击事件过度
    };
  },
  mounted() {
     
    window.addEventListener("scroll", () => {
     
      let top =
        document.documentElement.scrollTop ||
        document.body.scrollTop ||
        window.pageYOffset;
      this.scrollNum = top;
      if (top >= 100) {
     
        this.isTop = true;
      } else {
     
        this.isTop = false;
      }
    });
  },
  1. 回到顶部按钮 div

    <div
      class="goTop iconfont ml-gotop"
      :class="isTop ? 'goTopAfter' : ''" 
      @click="goTop()"
    >div>
  1. 回到顶部方法
	goTop() {
     
      if (this.myTimer == -1) {
     
        this.myTimer = setInterval(() => {
     
          this.scrollNum -= 60;
          if (this.scrollNum <= 0) {
     
            this.scrollNum = 0;
            window.clearInterval(this.myTimer); //停止执行
            this.myTimer = -1;
          }
          window.scrollTo(0, this.scrollNum); //离开网页顶部的距离
        }, 10);
      }
    },
  1. 按钮样式
.goTop {
     
  position: fixed;
  bottom: -100px;
  right: 5%;
  width: 60px;
  height: 60px;
  border-radius: 30px;
  z-index: 10;
  background-color: rgba(33, 81, 129, 0.5);
  transition: 0.3s ease-in-out;
  font-size: 30px;
  text-align: center;
  line-height: 60px;
  color: #ffffff;
  transition: 0.3s ease-in-out;
  cursor: pointer;
}
.goTop:hover {
     
  background-color: rgba(33, 81, 129, 1);
  transition: 0.3s ease-in-out;
}
.goTopAfter {
     
  transition: 0.3s ease-in-out;
  bottom: 100px;
}

你可能感兴趣的:(前端,vue,js,css,javascript,html5)