<template>
  <div class="affix">
    <div class="back-to-top" v-show="isshow" @click="onBackToTop">
      <ArrowUp class="w-6" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { ArrowUp } from '@element-plus/icons-vue';

const isshow = ref(false)
onMounted(() => {
  window.addEventListener("scroll", () => {
    const scrolltop = document.getElementById('content')?.scrollTop;
    if (scrolltop !== undefined) {
      if (scrolltop >= 50) {
        isshow.value = true;
      }
      if (scrolltop == 0) {
        isshow.value = false;
      }
    }
  }, true);
})
function onBackToTop() {
  let top = document.getElementById('content')?.scrollTop //获取点击时页面的滚动条纵坐标位置
  const timeTop = setInterval(() => {
    const contentHtml = document.getElementById('content')
    if (contentHtml !== null && top !== undefined) {
      contentHtml.scrollTop = top -= 180 //一次减180往上滑动
      if (top <= 0) {
        clearInterval(timeTop)
      }
    }
  }, 10) //定时调用函数使其更顺滑
}
</script>

<style scoped lang="scss">
.affix {
  position: fixed;
  z-index: 9999;
  bottom: 40px;
  right: 40px;

  .back-to-top {
    cursor: pointer;
    width: 40px;
    height: 40px;
    border: 2px solid #000;
    border-radius: 50%;
    transition: none;
    display: flex;
    justify-content: center;
    align-items: center;

    &:hover {
      transform: scale(1.2);
    }
  }
}
</style>

<style lang="scss" scoped>
.is-dark.back-to-top {
  color: #fff;
  border: 2px solid #fff;
}
</style>