vue 返回顶部

308 阅读1分钟
<template>
  <div id="goTop">
    <img
      class="opacity"
      ref="div"
      src="https://profile.csdnimg.cn/A/1/4/2_weixin_30700099"
      @click="top"
    >
  </div>
</template>
<script>
var timer = null;
export default {
  data() {
    return {};
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
  },

  methods: {
    showa() {
      this.show = true;
      console.log(this.$refs.div);
    },
    handleScroll() {
      let that = this;
      var scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      console.log(scrollTop);
      var div = that.$refs.div;
      if (scrollTop > 500) {
        div.style.opacity = 1;
      } else {
        div.style.opacity = 0;
      }
    },
      top() {
      // 设置定时器
      timer = setInterval(function() {
        // 获取滚动条,距离顶部的高度(适配IE浏览器,google浏览器)
        var osTop =
          document.documentElement.scrollTop || document.body.scrollTop;
        var iSpeed = Math.floor(-osTop / 7); // 小数点,向下舍入。
        // this.isTop = true;
        document.documentElement.scrollTop = document.body.scrollTop =
          osTop + iSpeed;
        if (osTop <= 0) {
          clearInterval(timer);
        }
        console.log("111111");
      }, 10);
    }
  }
};
</script>
 
<style scoped>
.opacity {
  position: fixed;
  bottom: 0;
  right: 0;
  opacity: 0;
  transition: 3s;
}

#goTop {
  width: 100%;
  height: 3000px;
  background: #eee;
}
</style>

希望能帮到你