<!DOCTYPE html>
<html>
<head>
<title>html基础</title>
<meta charset="UTF-8">
</head>
<style>
*{
padding: 0;
margin: 0;
}
.box{
width: 500px;
height: 500px;
background-color: pink;
position: relative;
}
</style>
<body>
<button id="btn" onclick="fn()">弹出球</button>
<div class="box" id="box">
</div>
</div>
<script>
var obox= document.getElementById('box')
var colors=['red','black','white','green','yellow']
function fn() {
var oball= document.createElement('div')
oball.style.cssText='border-radius: 50%;box-shadow: 1px 2px #666;position: absolute;background-color:red'
var wh=Math.floor(Math.random()*(50-20)+20)
oball.style.width=wh+'px'
oball.style.height=wh+'px'
oball.style.backgroundColor=colors[Math.floor(Math.random()*colors.length)]
obox.appendChild(oball)
var top = obox.clientHeight/2 - oball.offsetHeight/2;//?
var left = obox.clientWidth/2 - oball.offsetWidth/2;//?
oball.style.left=left+'px'
oball.style.top=top+'px'
var x=Math.floor(Math.random()*(7-2)+2)
var y=Math.floor(Math.random()*(7-2)+2)
setInterval(function () {
left+=x
top+=y
if (left< obox.offsetLeft || left > (obox.offsetLeft+obox.offsetWidth-oball.offsetWidth)) {
x = -x
}
if (top < obox.offsetTop || top > (obox.offsetTop+obox.offsetHeight-oball.offsetHeight-3)) {
y = -y
}
oball.style.left=left+"px";
oball.style.top=top+"px";
}, 30)
}
</script>
</body>
</html>