使用css3制作下雨动画的效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rain Effect</title>
<style>
body {
background-color: #222;
overflow: hidden; /* Prevent scrollbars */
}
.rain {
position: absolute;
top: 0;
left: 0;
width: 1px;
height: 100px;
background: linear-gradient(to bottom, rgba(255,255,255,0), rgba(255,255,255,1));
animation: rain-fall 1s linear infinite;
}
.rain::before {
content: '';
position: absolute;
bottom: 0;
left: 0;
width: 1px;
height: 10px;
background: rgba(255,255,255,1);
animation: rain-splash .2s linear infinite; /* Splash effect */
}
@keyframes rain-fall {
0% {
transform: translateY(-100px);
}
100% {
transform: translateY(calc(100vh + 100px)); /* Fall off screen */
}
}
@keyframes rain-splash {
0% { transform: scaleY(1); opacity: 1; }
50% { transform: scaleY(2); opacity: 0.5; }
100% { transform: scaleY(1); opacity: 0; }
}
/* Generate multiple rain drops */
.rain-container {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none; /* Allow interaction with elements behind the rain */
}
</style>
</head>
<body>
<div class="rain-container">
</div>
<script>
const container = document.querySelector('.rain-container');
const numDrops = 200; // Adjust number of raindrops
for (let i = 0; i < numDrops; i++) {
const drop = document.createElement('div');
drop.classList.add('rain');
drop.style.left = `${Math.random() * 100}%`;
drop.style.animationDelay = `${Math.random() * 0.5}s`; // Randomize start time
drop.style.animationDuration = `${Math.random() * 0.5 + 0.5}s`; // Randomize speed
container.appendChild(drop);
}
</script>
</body>
</html>
Key improvements and explanations:
overflow: hidden;
onbody
: Prevents scrollbars from appearing due to the rain extending beyond the viewport.pointer-events: none;
on.rain-container
: This is crucial. It makes the rain drops non-interactive, allowing you to click or interact with elements behind the rain effect.- Splash Effect (
::before
pseudo-element): Adds a small splash animation at the bottom of each rain drop using the::before
pseudo-element and a separate animation. - Randomized Animation:
animationDelay
andanimationDuration
are randomized for each drop to create a more natural and less uniform look. The duration is randomized between 0.5s and 1s. calc(100vh + 100px)
inrain-fall
animation: Ensures the rain drops fall completely off-screen before restarting their animation cycle, preventing any flickering at the top.- Comments: Added comments to explain the purpose of different parts of the code.
numDrops
variable: Makes it easy to control the number of rain drops.
How to use:
- Save the code as an HTML file (e.g.,
rain.html
). - Open the file in a web browser.
This improved version provides a more realistic and visually appealing rain effect while also ensuring it doesn't interfere with the usability of the rest of your webpage. You