思路:
1.创建一个放置小球的盒子
2.定义一个定时器,记录随机小球出现的时间
3.创建一个小球,并且得给它设置样式
4.利用Math.random个创建得小球定义随机的大小,颜色和位置
5.将创建的这个小球追加到刚开始创建的盒子里面
样式
* {
margin: 0;
padding: 0;
}
body {
background-color: black;
}
div .wrap {
position: relative;
}
.wrap div {
position: absolute;
border-radius: 80px;
}
<div class="wrap"></div>
js代码
var wrap = document.getElementsByTagName('div')[0];
var timer = setInterval(randomball, 50);
var num = 0;
function randomball() {
num++;
//1创建
var div = document.createElement('div');
//随即大小
var wh = ranFun(3, 30);
div.style.width = wh + 'px';
div.style.height = wh + 'px';
//随机颜色
var r = ranFun(0, 255);
var g = ranFun(0, 255);
var b = ranFun(0, 255);
div.style.backgroundColor = 'rgba(' + r + ',' + g + ',' + b + ')';
//随机位置
div.style.left = ranFun(0, window.innerWidth - wh) + 'px';
div.style.top = ranFun(0, window.innerHeight - wh) + 'px';
//2追加
wrap.appendChild(div);
if (num >= 100) {
clearInterval(timer);
}
}
function ranFun(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min)
}