Hanye官网
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BackToTop.vue 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <template>
  2. <div
  3. v-show="showBackToTop"
  4. @click="scrollToTop"
  5. class="fixed right-5 bottom-5 bg-stone-800 hover:bg-stone-700 text-white w-10 h-10 rounded-full flex items-center justify-center cursor-pointer transition-all duration-300 z-50 shadow-lg"
  6. :aria-label="t('common.backToTop')"
  7. >
  8. <svg
  9. xmlns="http://www.w3.org/2000/svg"
  10. class="h-5 w-5"
  11. viewBox="0 0 20 20"
  12. fill="currentColor"
  13. >
  14. <path
  15. fill-rule="evenodd"
  16. d="M14.707 12.707a1 1 0 01-1.414 0L10 9.414l-3.293 3.293a1 1 0 01-1.414-1.414l4-4a1 1 0 011.414 0l4 4a1 1 0 010 1.414z"
  17. clip-rule="evenodd"
  18. />
  19. </svg>
  20. </div>
  21. </template>
  22. <script setup lang="ts">
  23. /**
  24. * 返回顶部按钮组件
  25. * 当页面滚动超过一定距离时显示,点击后平滑滚动回顶部
  26. */
  27. import { useI18n } from 'vue-i18n';
  28. const { t } = useI18n();
  29. const showBackToTop = ref(false);
  30. const scrollThreshold = 300; // 显示按钮的滚动阈值
  31. /**
  32. * 监听滚动事件,控制按钮显示
  33. */
  34. function checkScroll() {
  35. showBackToTop.value = window.scrollY > scrollThreshold;
  36. }
  37. /**
  38. * 滚动到页面顶部
  39. */
  40. function scrollToTop() {
  41. window.scrollTo({
  42. top: 0,
  43. behavior: "smooth",
  44. });
  45. }
  46. // 生命周期钩子
  47. onMounted(() => {
  48. window.addEventListener("scroll", checkScroll);
  49. checkScroll(); // 初始检查
  50. });
  51. onUnmounted(() => {
  52. window.removeEventListener("scroll", checkScroll);
  53. });
  54. </script>