函数:这个函数是进过优化的,尽量减少重绘回流,并考虑了屏幕分辩率,如果还能优化或有问题可以回复我,促进成长呀。
export const rain = (className) => {
var content = document.querySelector("." + className);
let height=window.screen.width;
let clone=content.cloneNode(true);
for (let i = 0; i < 30; i++) {
let rain = document.createElement("div");
rain.setAttribute("class", "rain");
let posNum = 0;
let num = Math.random() * (height-20);
let time = Math.random() * 10;
posNum += num;
rain.style.cssText=`left:${posNum}px;top:${0}px;animation-delay:${time}s`;
clone.appendChild(rain);
}
content.parentNode.replaceChild(clone, content);
};
传入的className对应的标签需要满足的条件
height:100%;
100%;
position: relative;
雨水样式:
//落雨动画样式
.rain{
position: absolute;
opacity: 0;
1px;
height: 60px;
background: #4E4E51;
pointer-events: none;
animation: drops 0.5s linear infinite;
}
@keyframes drops{
0%{
opacity: 0;
}
20%{
opacity: 1;
}
95%{
opacity: 1;
}
100%{
opacity: 0;
transform: translate3d(0px,90vh,0px);/*斜度,向下,空间感*/
}
}
使用示例,下面代码只是使用方法,我是用txt写的,语法可能有误。
<style>
html{
height:100%;
100%;
}
.full-screen{
height:100%;
100%;
}
.pos{
position: relative;
}
.rain{
position: absolute;
opacity: 0;
1px;
height: 60px;
background: #4E4E51;
pointer-events: none;
animation: drops 0.5s linear infinite;
}
@keyframes drops{
0%{
opacity: 0;
}
20%{
opacity: 1;
}
95%{
opacity: 1;
}
100%{
opacity: 0;
transform: translate3d(0px,90vh,0px);/*斜度,向下,空间感*/
}
}
</style>
<body class="full-screen">
<div class="full-screen pos">
<div>
</body>
<script>
window.onload=()=>{
rain('pos');
}
rain = (className) => {
var content = document.querySelector("." + className);
let height=window.screen.width;
let clone=content.cloneNode(true);
for (let i = 0; i < 30; i++) {
let rain = document.createElement("div");
rain.setAttribute("class", "rain");
let posNum = 0;
let num = Math.random() * (height-20);
let time = Math.random() * 10;
posNum += num;
rain.style.cssText=`left:${posNum}px;top:${0}px;animation-delay:${time}s`;
clone.appendChild(rain);
}
content.parentNode.replaceChild(clone, content);
};
</script>