<template>
  <div class='sakura-container'>
    <div v-for='(sakura, index) in sakuras' :key='index' :style='sakura.style' class='sakura'></div>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        sakuras: [],
        timer: null,
        containerWidth: 0,
      };
    },
    mounted() {
      this.initSakuras();
      this.startAnime();
      window.addEventListener('resize', this.initSakuras);
    },
    beforeUnmount() {
      window.removeEventListener('resize', this.initSakuras);
    },
    methods: {
      // 初始化樱花
      initSakuras() {
        this.containerWidth = this.$el.clientWidth;
        this.sakuras = [];
        for (let i = 0; i < 30; i++) {
          this.sakuras.push({
            style: {
              left: Math.random() * this.containerWidth + 'px',
              top: Math.random() * -100 - 50 + 'px',
              animationDelay: Math.random() * 5 + 's',
            },
          });
        }
      },
      // 开始动画
      startAnime() {
        this.timer = setInterval(() => {
          this.sakuras.forEach((sakura) => {
            const top = parseFloat(sakura.style.top);
            if (top >= window.innerHeight + 50) {
              sakura.style.top = Math.random() * -100 - 50 + 'px';
              sakura.style.left = Math.random() * this.containerWidth + 'px';
            } else {
              sakura.style.top = top + 1 + 'px';
            }
          });
        }, 20);
      },
    },
  };
</script>
<style>
  .sakura-container {
    position: relative;
    height: 100%;
    overflow: hidden;
  }
  .sakura {
    position: absolute;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background-color: #fff;
    opacity: 0.7;
    animation: sakura-fall 10s linear infinite;
  }
  @keyframes sakura-fall {
    to {
      transform: translateY(100vh);
    }
  }
</style>
<p>通过 <code>initSakuras</code> 方法初始化樱花,通过 <code>startAnime</code> 方法开始动画。在动画中,通过遍历 <code>sakuras</code> 数组,逐个更新每个樱花的 <code>top</code> 值,实现樱花飘落的效果。同时,当樱花飘落到屏幕下方时,重新设置 <code>top</code> 和 <code>left</code> 值,让樱花重新回到屏幕顶部。</p>
<p>在样式中,设置了一个 <code>.sakura</code> 类来定义樱花的样式,同时使用了 CSS 动画 <code>sakura-fall</code> 来实现樱花的下落效果。在模板中,通过 <code>v-for</code> 指令遍历 <code>sakuras</code> 数组,生成多个樱花组件。</p>

原文地址: https://www.cveoy.top/t/topic/oaPp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录