飞舞的气泡
程序员文章站
2022-03-03 22:29:55
...
飞舞的气泡
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
p {
text-align: center;
}
.container {
position: relative;
width: 500px;
height: 500px;
border: 1px solid #ccc;
background-color: #fbfbfb;
margin: auto;
}
.container > .ball {
position: absolute;
border-radius: 50%;
box-shadow: 0 0 10px #888888 inset;
}
</style>
</head>
<body>
<p>
<button id="pup-ball">弹球</button>
</p>
<div class="container"></div>
<script>
document.getElementById('pup-ball').onclick = function () {
var box = document.getElementsByClassName('container')[0],
ball = document.createElement('div'),
size = 20 + Math.floor(Math.random() * 5) * 10,
color = ['yellow', 'green', 'blue', 'purple', 'red'][Math.floor(Math.random() * 5)],
stepx = (5 + Math.floor(Math.random() * 10)) * ([-1, 1].sort((a, b) => Math.random() - 0.5).shift()),
stepy = (5 + Math.floor(Math.random() * 10)) * ([-1, 1].sort((a, b) => Math.random() - 0.5).shift()),
top = box.clientWidth / 2 - size / 2,
left = box.clientHeight / 2 - size / 2;
ball.setAttribute('class', 'ball');
box.appendChild(ball);
var timer = setInterval(function () {
ball.style.cssText = `width:${size}px;height:${size}px;background:${color};top:${top}px;left:${left}px`;
top += stepy
if (top < 0 || top > box.clientHeight - size) stepy = -stepy;
left += stepx;
if (left < 0 || left > box.clientWidth - size) stepx = -stepx;
}, 30)
}
</script>
</body>
</html>