<html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style>
#main {
width:800px;
height:600px;
background: #ccc;
position: relative;
}
ball{
}
</style>
</head>
<body>
<input type="button" value="弹出球" id="btn">
<div id="main">
</div>
<script>
var main = document.getElementById('main');
var btn = document.getElementById('btn');
btn.onclick = function () {
var color = "#"+parseInt(Math.random()*1000);
var wh = Math.floor(Math.random()*50)+20;
var ball = document.createElement('div')
ball.style.cssText = 'position: absolute;border-radius: 50%;'
ball.style.background = color;
ball.style.width = wh+'px';
ball.style.height = wh+'px';
var top = main.clientHeight/2 - wh;
var left = main.clientWidth/2 - wh;
ball.style.top = top+'px';
ball.style.left = left+'px';
main.appendChild(ball)
var x = Math.floor(Math.random()*20)+1
var y = Math.floor(Math.random()*20)+1
setInterval(function () {
left+=x;
top+=y;
if (left<=main.offsetLeft || left > (main.offsetLeft+main.offsetWidth-ball.offsetWidth) ){
x = -x;
}
if (top<=main.offsetTop || top > (main.offsetTop+main.offsetHeight-ball.offsetHeight-3)){
y= -y;
}
ball.style.left = left
ball.style.top = top
},100)
}
</script>
</body>
</html>
相关推荐
© 2020 asciim码
人生就是一场修行