用 JS 实现的彩色雨
AWS 安全上线!
在本文中,我们将使用 JS 构建一个可以生成雨滴的容器。雨滴的颜色是随机的,色彩丰富。您可以随意调整颜色。首先,让我们看看我们要构建什么。
预览
现在让我们看看代码,看看如何让它工作。
HTML
<div class="rain-container"></div>
CSS
* {
margin: 0;
padding: 0;
}
.rain-container {
position: relative;
background: #000;
width: 100vw;
height: 100vh;
overflow: hidden;
}
i {
position: absolute;
height: 120px;
border-radius: 0 0 999px 999px;
animation: animate 5s linear infinite;
}
@keyframes animate {
0% {
transform: translateY(-120px);
}
100% {
transform: translateY(calc(100vh + 120px));
}
}
JavaScript
const rainContainer = document.querySelector(".rain-container");
// background Colors for the raindrop
const background = [
"linear-gradient(transparent, aqua)",
"linear-gradient(transparent, red)",
"linear-gradient(transparent, limegreen)",
"linear-gradient(transparent, white)",
"linear-gradient(transparent, yellow)"
];
const amount = 100; // amount of raindops
let i = 0;
// Looping and creating the raindrop then adding to the rainContainer
while (i < amount) {
// Creating and Element
const drop = document.createElement("i");
// CSS Properties for raindrop
const raindropProperties = {
width: Math.random() * 5 + "px",
positionX: Math.floor(Math.random() * window.innerWidth) + "px",
delay: Math.random() * -20 + "s",
duration: Math.random() * 5 + "s",
bg: background[Math.floor(Math.random() * background.length)],
opacity: Math.random() + 0.2
};
// Setting Styles for raindrop
drop.style.width = raindropProperties.width;
drop.style.left = raindropProperties.positionX;
drop.style.animationDelay = raindropProperties.delay;
drop.style.animationDuration = raindropProperties.duration;
drop.style.background = raindropProperties.bg;
drop.style.opacity = raindropProperties.opacity;
// Appending the raindrop in the raindrop container
rainContainer.appendChild(drop);
i++;
}
总结
就是这样。你可以轻松做到这一点,甚至可以更上一层楼。如果你喜欢这篇文章,别忘了点赞❤️。如果你有任何疑问或建议,请随时提出。再见。