<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snowflake Animation</title>
<style>
body, html {
margin: 0;
padding: 0;
height: 100%;
}
.snowflake {
position: fixed;
background-color: white;
border-radius: 50%;
transform: translate(-50%, -100%);
pointer-events: none;
}
</style>
</head>
<body>
<script>
class Snowflake {
constructor() {
this.snowflake = document.createElement('div');
this.snowflake.classList.add('snowflake');
this.size = Math.random() * 10 + 10;
this.speed = Math.random() * 2 + 1;
this.x = Math.random() * window.innerWidth;
this.y = Math.random() * -window.innerHeight;
this.snowflake.style.width = `${this.size}px`;
this.snowflake.style.height = `${this.size}px`;
document.body.appendChild(this.snowflake);
this.update();
}
update() {
this.y += this.speed;
this.snowflake.style.transform = `translate(${this.x}px, ${this.y}px)`;
if (this.y > window.innerHeight) {
this.snowflake.remove();
}
requestAnimationFrame(() => this.update());
}
}
const snowflakes = [];
for (let i = 0; i < 50; i++) {
snowflakes.push(new Snowflake());
}
</script>
</body>
</html>
这段代码创建了一个简单的雪花飘落效果。它使用了JavaScript中的类来构建每个雪花对象,每个对象都有自己的大小、速度和初始位置。每个雪花的CSS类定义了基本的样式,并且JavaScript代码负责更新每个雪花的位置,并移除那些移出屏幕的雪花。这个简单的示例展示了如何用JavaScript和CSS创建交互式动画效果。