直接上代码
<!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>Document</title>
<style>
@keyframes whereabouts {
0% {
top: 0;
}
100% {
top: calc(100vh - 112px);
}
}
</style>
</head>
<body>
</body>
<script>
const getRndInteger = (min, max) => {
return Math.floor(Math.random() * (max - min)) + min;
}
const dislocateFun = (num, arr = []) => {
let newArr = []
for (let i = 0; i < num; i++) {
const index = getRndInteger(0, arr.length);
newArr.push(arr[index]);
};
return newArr
}
const init = (snowArr = [], snowNumber, isInfinite) => {
const body = document.querySelector('body');
body.style.position = 'relative';
const randomNewArray = dislocateFun(snowNumber, snowArr);
let strHtml = ''
randomNewArray.forEach((item, index) => {
const span = document.createElement('span');
span.innerText = item;
span.className = `span__${index + 1}`;
span.style.position = 'absolute';
const num = getRndInteger(0, body.clientWidth);
span.style.left = `${num}px`;
span.style.animationName = 'whereabouts';
const s = (Math.random() * 8) + 1
span.style.animationDuration = `${s}s`;
span.style.animationIterationCount = isInfinite ? 'infinite' : 1;
span.style.animationFillMode = "forwards"
span.style.animationTimingFunction = 'ease';
body.appendChild(span);
if (!isInfinite) {
span.addEventListener('webkitAnimationEnd', () => {
span.remove();
})
}
})
}
/**
*
* @param {Array} snowArr 下落的字或者其他
* @param {Number} snowNumber 下落的数量
* @param {Boolean} isInfinite 是否需要循环下落
*/
init(['雪', '雨',], 100, true);
</script>
</html>