
<template>
  <div class="goTop-box">
    <!-- 返回顶部 -->
    <img src="../../assets/image/goTop.png" v-if="btnFlag" @click="backTop" alt class="go-top" />
  </div>
</template>
 
<script>
name: "goTop";
export default {
  data() {
    return {
      btnFlag: false // 返回顶部
    };
  },

  mounted() {
    var _this = this;
    window.addEventListener("scroll", _this.scrollToTop());
  },
  destroyed() {
    var _this = this;
    window.removeEventListener("scroll", _this.scrollToTop());
  },

  methods: {
    // 点击图片回到顶部方法，加计时器是为了过渡顺滑
    backTop() {
      const that = this;
      let timer = setInterval(() => {
        let ispeed = Math.floor(-that.scrollTop / 5);
        document.documentElement.scrollTop = document.body.scrollTop =
          that.scrollTop + ispeed;
        if (that.scrollTop === 0) {
          clearInterval(timer);
        }
      }, 16);
    },

    // 为了计算距离顶部的高度，当高度大于60显示回顶部图标，小于60则隐藏
    scrollToTop() {
      const that = this;
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      that.scrollTop = scrollTop;
      that.gotop = that.scrollTop;
      // localStorage.setItem("heightA", that.gotop);
      if (that.scrollTop > 60) {
        that.btnFlag = true;
      } else {
        // that.btnFlag = false;
        that.btnFlag = true;
      }
    }
  }
};
</script>
 
<style>
.goTop-box .go-top {
  position: fixed;
  right: 0.5rem;
  bottom: 1rem;
  width: 1rem;
  height: 1rem;
  z-index: 100;
}
</style>