夏天在南方最常见的就是高温和下雨了,我们就用js+css做一个下雨的页面吧
1、html
我们先把内容区域写好,
css
html, body { height: 100%; width: 100%; background-color: rgba(0, 0, 0, .5); overflow: hidden;}.content { height: 100%;}#rainBox { height: 100%;}.rain { position: absolute; width: 2px; height: 50px; background: linear-gradient(rgba(255,255,255,.3), rgba(255,255,255,.66));}
html
<div id="app"> <div class="content"> <div id="rainBox"></div> </div></div>
2、制作单个雨滴
雨滴采用js方式动态添加,所以我们只需要书写样式即可,这里把雨滴做成一个渐变色的效果
.rain { width: 2px; height: 50px; background: linear-gradient(rgba(255,255,255,.3), rgba(255,255,255,.66));}
3、雨滴的运动
雨滴的div用绝对定位固定初始位置,top = 0,left随机,赋予出现位置的随机性
声明一个初始值为1的变量gap
使用js动态修改其top,使其移动落下,位置在gap上增加,gap也相应增加1,使其有一个加速度下落的效果
定时器每隔20ms执行上述逻辑,当雨滴的top值超过了屏幕高度的时候,就把该元素移除
rain.style.top = 0;rain.style.left = `${Math.random() * boxWidth}px`;let gap = 1;const loop = setInterval(() => { if (parseInt(rain.style.top) > boxHeight) { clearInterval(loop);box.removeChild(rain) } gap++ rain.style.top = `${parseInt(rain.style.top)+gap}px`;}, 20)
4、雨滴的添加
let rain = document.createElement('div');rain.classList.add('rain');
5、雨滴的移除
box.removeChild(rain)
完成代码
完成了单个雨滴的从开始到下落,最后用定时器,批量随机生成大量雨滴
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <title></title> <style> * { margin: 0; padding: 0; } html, body { height: 100%; width: 100%; background-color: rgba(0, 0, 0, .5); overflow: hidden; } .content { height: 100%; } #rainBox { height: 100%; } .rain { position: absolute; width: 2px; height: 50px; background: linear-gradient(rgba(255,255,255,.3), rgba(255,255,255,.66)); } </style> </head> <body> <div class="content"> <div id="rainBox"></div> </div> <script> const box = document.getElementById('rainBox'); let boxHeight = box.clientHeight; let boxWidth = box.clientWidth; window.onresize = function() { boxHeight = box.clientHeight; boxWidth = box.clientWidth; } function rainDot() { let rain = document.createElement('div'); rain.classList.add('rain'); rain.style.top = 0; rain.style.left = `${Math.random() * boxWidth}px`; rain.style.opacity = Math.random(); box.appendChild(rain); let gap = 1; const loop = setInterval(() => { if (parseInt(rain.style.top) > boxHeight) { clearInterval(loop); box.removeChild(rain) } gap++ rain.style.top = `${parseInt(rain.style.top)+gap}px`; }, 20) } setInterval(() => { rainDot(); }, 50) </script> </body></html>原文:https://juejin.cn/post/7101531420765454344