<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>雪花飘落效果</title>
<style>
body {
margin: 0;
overflow: hidden;
background: linear-gradient(to bottom, #1e3c72, #2a5298);
height: 100vh;
}
.snowflake {
position: absolute;
color: white;
font-size: 1em;
user-select: none;
pointer-events: none;
animation: fall linear forwards;
}
@keyframes fall {
to {
transform: translateY(100vh);
}
}
</style>
</head>
<body>
<script>
// 创建雪花
function createSnowflakes() {
// 雪花数量 - 根据屏幕宽度调整
const snowflakeCount = Math.floor(window.innerWidth / 10);
for (let i = 0; i < snowflakeCount; i++) {
createSnowflake();
}
}
// 创建单个雪花
function createSnowflake() {
const snowflake = document.createElement('div');
snowflake.className = 'snowflake';
// 随机选择雪花形状(可以使用Unicode雪花符号或自定义)
const snowflakeSymbols = ['❄', '❅', '❆', '✻', '✼', '❄', '❅'];
const randomSymbol = snowflakeSymbols[Math.floor(Math.random() * snowflakeSymbols.length)];
snowflake.textContent = randomSymbol;
// 随机大小
const size = Math.random() * 1.5 + 0.5;
snowflake.style.fontSize = `${size}em`;
// 随机透明度
const opacity = Math.random() * 0.7 + 0.3;
snowflake.style.opacity = opacity;
// 随机起始位置
const startX = Math.random() * window.innerWidth;
const startY = -20;
snowflake.style.left = `${startX}px`;
snowflake.style.top = `${startY}px`;
// 随机动画持续时间(下落速度)
const duration = Math.random() * 10 + 5;
snowflake.style.animationDuration = `${duration}s`;
// 随机延迟开始时间
const delay = Math.random() * 5;
snowflake.style.animationDelay = `${delay}s`;
// 随机摆动效果
const sway = Math.random() * 50 - 25;
snowflake.style.animationName = `fall, sway${Math.random() > 0.5 ? '1' : '2'}`;
document.body.appendChild(snowflake);
// 动画结束后移除雪花并创建新的
snowflake.addEventListener('animationend', () => {
snowflake.remove();
createSnowflake();
});
}
// 添加摆动动画
function addSwayAnimations() {
const style = document.createElement('style');
style.textContent = `
@keyframes sway1 {
0%, 100% { transform: translateX(0) translateY(0); }
50% { transform: translateX(${Math.random() * 50 - 25}px) translateY(${Math.random() * 10}px); }
}
@keyframes sway2 {
0%, 100% { transform: translateX(0) translateY(0); }
50% { transform: translateX(${Math.random() * 50 - 25}px) translateY(${Math.random() * 10}px); }
}
`;
document.head.appendChild(style);
}
// 初始化
window.addEventListener('load', () => {
addSwayAnimations();
createSnowflakes();
});
// 窗口大小改变时重新调整雪花数量
window.addEventListener('resize', () => {
const snowflakes = document.querySelectorAll('.snowflake');
snowflakes.forEach(snow => snow.remove());
createSnowflakes();
});
</script>
</body>
</html>