欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

飞舞的气泡

程序员文章站 2022-03-03 22:29:55
...

飞舞的气泡

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. <style>
  7. p {
  8. text-align: center;
  9. }
  10. .container {
  11. position: relative;
  12. width: 500px;
  13. height: 500px;
  14. border: 1px solid #ccc;
  15. background-color: #fbfbfb;
  16. margin: auto;
  17. }
  18. .container > .ball {
  19. position: absolute;
  20. border-radius: 50%;
  21. box-shadow: 0 0 10px #888888 inset;
  22. }
  23. </style>
  24. </head>
  25. <body>
  26. <p>
  27. <button id="pup-ball">弹球</button>
  28. </p>
  29. <div class="container"></div>
  30. <script>
  31. document.getElementById('pup-ball').onclick = function () {
  32. var box = document.getElementsByClassName('container')[0],
  33. ball = document.createElement('div'),
  34. size = 20 + Math.floor(Math.random() * 5) * 10,
  35. color = ['yellow', 'green', 'blue', 'purple', 'red'][Math.floor(Math.random() * 5)],
  36. stepx = (5 + Math.floor(Math.random() * 10)) * ([-1, 1].sort((a, b) => Math.random() - 0.5).shift()),
  37. stepy = (5 + Math.floor(Math.random() * 10)) * ([-1, 1].sort((a, b) => Math.random() - 0.5).shift()),
  38. top = box.clientWidth / 2 - size / 2,
  39. left = box.clientHeight / 2 - size / 2;
  40. ball.setAttribute('class', 'ball');
  41. box.appendChild(ball);
  42. var timer = setInterval(function () {
  43. ball.style.cssText = `width:${size}px;height:${size}px;background:${color};top:${top}px;left:${left}px`;
  44. top += stepy
  45. if (top < 0 || top > box.clientHeight - size) stepy = -stepy;
  46. left += stepx;
  47. if (left < 0 || left > box.clientWidth - size) stepx = -stepx;
  48. }, 30)
  49. }
  50. </script>
  51. </body>
  52. </html>

飞舞的气泡