ParallaxBackground.vue 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <template>
  2. <div ref="containerRef" class="fixed inset-0 overflow-hidden">
  3. <Motion
  4. class="absolute inset-0 bg-cover bg-no-repeat"
  5. :style="backgroundStyle"
  6. />
  7. <div
  8. class="absolute inset-0 bg-gradient-to-b from-c via-transparent to-white z-0"
  9. />
  10. </div>
  11. </template>
  12. <script setup lang="ts">
  13. import { useScroll, useTransform, Motion } from 'motion-v';
  14. import { ref, computed } from 'vue';
  15. import bg2 from '@/assets/imgs/home/bg2.png';
  16. defineOptions({
  17. name: 'ParallaxBackground',
  18. });
  19. // 内容容器
  20. const containerRef = ref<HTMLElement | null>(null);
  21. // 滚动监听,监控整个文档的滚动
  22. const { scrollYProgress } = useScroll({
  23. offset: ['start start', 'end start'],
  24. });
  25. // 视差效果 - 大幅增加位移距离,向上移动
  26. const parallaxY = useTransform(
  27. scrollYProgress,
  28. [0, 1],
  29. ['0%', '-50%'], // 增大位移距离到50%
  30. );
  31. // 背景图样式
  32. const backgroundStyle = computed(() => ({
  33. backgroundImage: `url(${bg2})`,
  34. y: parallaxY,
  35. backgroundPosition: 'center top',
  36. backgroundSize: 'cover',
  37. height: '140%', // 图片高度超过容器
  38. }));
  39. </script>
  40. <style lang="scss" scoped></style>