思路:首先 搭建好 一个 ‘< i >’ 的样式 还用下落的动画
接着使用for循环 创建多个 并添加到body中
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Colorful Rain</title> <link rel="stylesheet" href="./index.css"> </head> <body> <script src="./index.js"></script> </body> </html>
*{ margin: 0; padding: 0; } body{ background-color: #000; min-height: 100vh; } i{ position: absolute; height: 200px; width: 4px; border-radius: 0 0 4px 4px; background-image: linear-gradient(transparent,#fff); animation: move 5s linear infinite; } i:nth-child(3n+1){ background-image: linear-gradient(transparent,rgb(241, 15, 15)); } i:nth-child(3n+2){ background-image: linear-gradient(transparent,rgb(14, 236, 218)); } i:nth-child(3n+3){ background-image: linear-gradient(transparent,rgb(36, 12, 248)); } @keyframes move { 0%{ transform: translateY(-200px); } 100%{ transform: translateY(calc(100vh + 200px)); } }
var count=100 var i=1 while (i<=count) { //创建 i var Ele=document.createElement("i") //i 的宽度 var EleW=Math.random()*5 //i的 left 屏幕距离 // left 就是屏幕的宽度随便跑 var wd=document.documentElement.clientWidth var EleLeft=Math.random()*(wd-EleW)+EleW //i 动画的随机时间1-5s var durTime=Math.random()*4+1 //i 延迟时间 var DelyTime=Math.random()*2 //添加样式 Ele.style.width=EleW+'px'; Ele.style.left=EleLeft+'px'; Ele.style.animationDuration=durTime+'s'; Ele.style.animationDelay=DelyTime+'s' //插入页面 document.body.append(Ele) i++ }