<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#box {
width: 500px;
height: 500px;
background: #EEEEEE;
border: 10px solid #FE3232;
position: relative;
margin: 0 auto;
}
.bool {
border-radius: 50%;
box-shadow: 2px 3px 5px #999999;
position: absolute;
}
</style>
</head>
<body>
<button id="add">add</button>
<div id="box">
</div>
<script>
function get_rand(little, big) {
return Math.floor(Math.random() * (big - little + 1)) + little;
}
var colorArr = [
'#FE3232',
'#ccdd22',
'#223355',
'#22aa66',
'#cc6699',
'#123456',
'#987654',
'#FEDCBA',
'#AB39EE',
'#985421'
]
var boxObj = document.getElementById('box');
var addObj = document.getElementById('add');
addObj.onclick = function () {
var nObj = document.createElement('div');
var wh = get_rand(10, 50);
nObj.style.width = wh + 'px';
nObj.style.height = wh + 'px';
nObj.style.background = colorArr[get_rand(0, 9)];
var top = boxObj.clientHeight / 2 - nObj.offsetHeight / 2;
var left = boxObj.clientWidth / 2 - nObj.offsetWidth / 2;
nObj.style.top = top + 'px';
nObj.style.left = left + 'px';
nObj.className = 'bool';
boxObj.appendChild(nObj);
var xx = get_rand(1, 10);
var yy = get_rand(1, 10);
setInterval(function () {
top += xx;
left += yy;
if (top > boxObj.clientHeight - nObj.offsetHeight || top < 0) {
xx = -xx;
}
if (left > boxObj.clientWidth - nObj.offsetWidth || left < 0) {
yy = -yy;
}
nObj.style.top = top + 'px';
nObj.style.left = left + 'px';
}, 50)
}
</script>
</body>
</html>