<template>
   <div
      v-show="showGoTopIcon"
      id="goToTop"
      class='go-to-top'
      @click="scrollToTop"
   >
      <img :src="goTopSrc">
   </div>

</template>
<script lang="ts">
import { Vue, Component } from 'vue-property-decorator';

@Component({
  components: {},
})
export default class ScrollTop extends Vue {
  private showGoTopIcon: boolean = false;
  private scrollTop: number = 0;
  // 換成自己專案的圖片位置
  private goTopSrc: string = '/backtotop.png';

  //////////////////// Vue Life ////////////////////
  private async beforeCreate() {}
  private async created() {}
  private async beforeMount() {}
  private async mounted() {
    this.$nextTick(() => window.addEventListener('scroll', this.showScrollToTopIcon, true));
  }
  private async beforeDestroy() {}
  private async destroyed() {
    window.removeEventListener('scroll', this.showScrollToTopIcon, true);
  }

  //////////////////// Scroll To Top ////////////////////
  private showScrollToTopIcon(e): void {
    // content 需要換成自己專案的class name
    let dom: any = document.getElementsByClassName('content')[0];
    this.scrollTop = dom.scrollTop;
    this.showGoTopIcon = this.scrollTop > 60;
  }

  private scrollToTop(): void {
    let timer: number = null;
    let _this: any = this;
    // content 需要換成自己專案的class name
    let dom: any = document.getElementsByClassName('content')[0];
    cancelAnimationFrame(timer);
    timer = requestAnimationFrame(function fn() {
      if (_this.scrollTop > 5000) {
        _this.scrollTop -= 1000;
        dom.scrollTop = _this.scrollTop;
        timer = requestAnimationFrame(fn);
      } else if (_this.scrollTop > 1000 && _this.scrollTop <= 5000) {
        _this.scrollTop -= 500;
        dom.scrollTop = _this.scrollTop;
        timer = requestAnimationFrame(fn);
      } else if (_this.scrollTop > 200 && _this.scrollTop <= 1000) {
        _this.scrollTop -= 100;
        dom.scrollTop = _this.scrollTop;
        timer = requestAnimationFrame(fn);
      } else if (_this.scrollTop > 50 && _this.scrollTop <= 200) {
        _this.scrollTop -= 10;
        dom.scrollTop = _this.scrollTop;
        timer = requestAnimationFrame(fn);
      } else if (_this.scrollTop > 0 && _this.scrollTop <= 50) {
        _this.scrollTop -= 5;
        dom.scrollTop = _this.scrollTop;
        timer = requestAnimationFrame(fn);
      } else {
        cancelAnimationFrame(timer);
        _this.showGoTopIcon = false;
      }
    });
  }
}

</script>

<style lang="scss" scoped>
.go-to-top {
   cursor: pointer;

   position: fixed;
   bottom: 5rem;
   right: 1.4rem;
   z-index: 999;
}
</style>

<!-- use  -->
<template>
   <ScrollTop/>
   <p>lorem500</p>
</template>

<script lang="ts">
import ScrollTop from './ScrollTop.vue';

@Component({
  components: {ScrollTop},
})
export default class UseScrollTop extends Vue {}

</script>

<style lang="scss" scoped>
</style>

    文章標籤

    HTML Vue

    全站熱搜

    bingzhichen 發表在 痞客邦 留言(0) 人氣()