在本文中,我们将使用 JS 构建一个生成雨水的容器。这是一场色彩随机的七彩雨。您可以随意使用颜色。首先,让我们看看我们在构建什么。
预览
在线演示地址:http://haiyong.site/qicaiyu
现在让我们看一下代码,我们如何让它工作。
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");
// 雨滴的背景颜色
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; // 雨滴的数量
let i = 0;
// 循环并创建雨滴,然后添加到rainContainer
while (i < amount) {
// 创建和元素
const drop = document.createElement("i");
// 雨滴的 CSS 属性
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
};
// 设置雨滴样式
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;
// 将雨滴添加到雨滴容器中
rainContainer.appendChild(drop);
i++;
}
完整源码关注公众号【海拥】回复【代码】获取
Java、Python、算法知识体系 | PPT、简历模板 | 游戏源码 | IT行业趣味资讯 | 装机必备软件
都可关注公众号【海拥】回复【资料】获取