<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#dv{
width: 600px;
height: 400px;
background-color: #ccc;
}
</style>
</head>
<body>
<input type="button" value="彈出球" id="btn">
<div id="dv">
</div>
<script>
var dv = document.getElementById('dv');
// var colors = ['red','yellow','blue','green','yellowgreen','#ff00ff']
var nums = ['.1','.2','.3','.4','.5','.6','.7','.8','.9','1']
document.getElementById('btn').onclick=function(){
var ball = document.createElement('div')
ball.style.cssText = "position:absolute;border-radius:50%;"
// 隨機寬高
var wh = (Math.floor(Math.random()*50) + 30) + 'px'
ball.style.width= wh;
ball.style.height= wh;
// 計算顏色
// ball.style.backgroundColor = colors[Math.floor(Math.random()*colors.length)];
ball.style.backgroundColor = 'rgba('+ Math.floor(Math.random()*255)+','+Math.floor(Math.random()*255) +','+Math.floor(Math.random()*255) +', '+nums[Math.floor(Math.random()*nums.length)]+')'
dv.appendChild(ball)
// 位置居中
var top = dv.clientHeight/2 - ball.offsetHeight/2;
var left = dv.clientWidth/2 - ball.offsetWidth/2;
// console.log(top)
// console.log(left)
// console.log(dv.clientWidth)
// console.log(dv.clientHeight)
// console.log(ball.offsetWidth)
// console.log(ball.offsetHeight)
ball.style.left = left + 'px';
ball.style.top = top + 'px';
var x = Math.floor(Math.random()*10) + 1;
var y = Math.floor(Math.random()*10) + 1;
setInterval(function(){
left += x;
top += y;
if(left < dv.offsetLeft || left >( dv.offsetLeft + dv.offsetWidth - ball.offsetWidth)){
x = -x
}
if(top < dv.offsetTop || top >(dv.offsetTop + dv.offsetHeight - ball.offsetHeight)){
y = -y
}
ball.style.left = left + 'px';
ball.style.top = top + 'px';
}, 30);
}
</script>
</body>
</html>