可以用js写一段樱花飘落的代码吗要兼容vue3
可以的,以下是一个简单的樱花飘落的代码,兼容Vue3:
<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>
通过 initSakuras 方法初始化樱花,通过 startAnime 方法开始动画。在动画中,通过遍历 sakuras 数组,逐个更新每个樱花的 top 值,实现樱花飘落的效果。同时,当樱花飘落到屏幕下方时,重新设置 top 和 left 值,让樱花重新回到屏幕顶部。
在样式中,设置了一个 .sakura 类来定义樱花的样式,同时使用了 CSS 动画 sakura-fall 来实现樱花的下落效果。在模板中,通过 v-for 指令遍历 sakuras 数组,生成多个樱花组件
原文地址: https://www.cveoy.top/t/topic/fjjn 著作权归作者所有。请勿转载和采集!