个人技术文章

CSS动画——雪花飘落效果实现

在Web开发中,下雪效果是一种常见的季节性动画。今天,我们将探讨如何使用CSS结合JavaScript实现自然的雪花飘落效果。

HTML结构

首先,我们需要创建一个容器来放置雪花:

<div class="snow-container" id="snowContainer"></div>

CSS实现

设置基本的样式和动画:

.snowflake { position: absolute; background: white; border-radius: 50%; pointer-events: none; opacity: 0.8; animation: snowfall linear infinite; } @keyframes snowfall { from { transform: translateY(-10px) rotate(0deg); } to { transform: translateY(410px) rotate(360deg); } }

JavaScript实现

使用JavaScript动态创建和控制雪花:

// 创建雪花函数 function createSnowflake() { const snowflake = document.createElement('div'); snowflake.className = 'snowflake'; const size = Math.random() * 4 + 2; const startingX = Math.random() * 100; const animationDuration = Math.random() * 3 + 2; snowflake.style.width = `${size}px`; snowflake.style.height = `${size}px`; snowflake.style.left = `${startingX}%`; snowflake.style.animationDuration = `${animationDuration}s`; return snowflake; }