随机小球
<!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>随机小球</title>
<style>
* {
margin: 0;
padding: 0;
}
html,
body {
width: 100%;
height: 100%;
}
body {
position: relative;
}
.dot {
position: absolute;
left: 0;
top: 0;
width: 100px;
height: 100px;
transition: all 1s ease-out;
border-radius: 50%;
}
</style>
</head>
<body>
<script>
window.onload = function () {
createEle(createNumber(50));
changeAnimation()
let timer = null;
const timeId = (func, interval) => {
func();
return setInterval(func, interval);
};
timer && clearInterval(timer);
timer = timeId(changeAnimation, 1000);
};
function createNumber(nums) {
let numberArr = [];
let index = 0;
do {
index++;
numberArr.push(index);
} while (index < nums)
return numberArr;
}
function createEle(smallNums) {
smallNums.forEach(() => {
let dot = document.createElement("div");
dot.setAttribute("class", "dot");
document.body.append(dot);
})
}
function getEle() {
let doms = document.getElementsByClassName("dot");
return Array.from(doms);
}
function getVariousVal(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function changeAnimation() {
let dotArr = getEle();
dotArr.forEach((item) => {
let dotLeft = getVariousVal(0, 1800);
let dotTop = getVariousVal(0, 800);
let rgb_one = getVariousVal(0, 225);
let rgb_two = getVariousVal(0, 225);
let rgb_three = getVariousVal(0, 225);
let opacity = Math.random().toFixed(1);
let circle = getVariousVal(0, 50);
setVariousVal(item, dotLeft, dotTop, rgb_one, rgb_two, rgb_three, opacity, circle);
})
}
function setVariousVal(ele, left, top, colorOne, colorTwo, colorThree, opacity, circle) {
ele.style.left = left + "px";
ele.style.top = top + "px";
ele.style.opacity = opacity;
ele.style.borderRadius = circle + "%";
ele.style.backgroundColor = `rgb(${colorOne},${colorTwo},${colorThree})`;
}
</script>
</body>
</html>