vue项目点击回到顶部

140 阅读1分钟

vue项目点击回到顶部

<template>
 <div id="back_to_top" ref="btn" @click="backTop" style="display: none;">
      <p style="font-size: 0.625em; font-weight: bold">TOP</p>
      <img src="../assets/other/launch.png" style="height: 45px;width: 35px;" />
  </div>
</template>
<script>
export default {
  data() {
    return {
      timer: "",
      scroll: "",
      isTitleFixed: false, // 是否固定标题
      lastScrollPosition: 0, // 上一次的滚动位置
      calleft: 0,
    };
  },
  methods: {
    backTop() {
      //当点击标签的时候,使用animate在200毫秒的时间内,滚到顶部
      this.timer = setInterval(() => {
        let osTop =
          document.documentElement.scrollTop || document.body.scrollTop;
        let ispeed = Math.floor(-osTop / 5);
        document.documentElement.scrollTop = document.body.scrollTop =
          osTop + ispeed;
        if (osTop === 0) {
          clearInterval(this.timer);
        }
      }, 30);
    },
    handleScroll() {
      this.scroll =
        document.documentElement.scrollTop + document.body.scrollTop; //获取滚动后的高度
      if (this.scroll > 600) {
        //判断滚动后高度超过400px,就显示
        this.$refs.btn.style.display = "block";
      } else {
        this.$refs.btn.style.display = "none";
      }
    },
  },
  mounted() {
    // 监听滚动事件
    window.addEventListener("scroll", this.handleScroll);
    this.autoPlay(); // 开始自动播放
  },
  beforeDestroy() {
    // 移除滚动事件监听
    window.removeEventListener("scroll", this.handleScroll);
    this.autoPlay();
  },
};
</script>
<style scoped>
  #back_to_top {
    position: fixed;
    bottom: 50px;
    right: 30px;
    cursor: pointer;
  }
</style>