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

位置属性 + 动画 = 飞舞的气泡

程序员文章站 2022-03-13 13:56:22
...
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. <style>
  7. #box {
  8. width: 500px;
  9. height: 500px;
  10. background: #EEEEEE;
  11. border: 10px solid #FE3232;
  12. position: relative;
  13. margin: 0 auto;
  14. }
  15. .bool {
  16. border-radius: 50%;
  17. box-shadow: 2px 3px 5px #999999;
  18. position: absolute;
  19. }
  20. </style>
  21. </head>
  22. <body>
  23. <button id="add">add</button>
  24. <div id="box">
  25. </div>
  26. <script>
  27. function get_rand(little, big) {
  28. return Math.floor(Math.random() * (big - little + 1)) + little;
  29. }
  30. var colorArr = [
  31. '#FE3232',
  32. '#ccdd22',
  33. '#223355',
  34. '#22aa66',
  35. '#cc6699',
  36. '#123456',
  37. '#987654',
  38. '#FEDCBA',
  39. '#AB39EE',
  40. '#985421'
  41. ]
  42. var boxObj = document.getElementById('box');
  43. var addObj = document.getElementById('add');
  44. addObj.onclick = function () {
  45. var nObj = document.createElement('div');
  46. var wh = get_rand(10, 50);
  47. nObj.style.width = wh + 'px';
  48. nObj.style.height = wh + 'px';
  49. nObj.style.background = colorArr[get_rand(0, 9)];
  50. var top = boxObj.clientHeight / 2 - nObj.offsetHeight / 2;
  51. var left = boxObj.clientWidth / 2 - nObj.offsetWidth / 2;
  52. nObj.style.top = top + 'px';
  53. nObj.style.left = left + 'px';
  54. nObj.className = 'bool';
  55. boxObj.appendChild(nObj);
  56. var xx = get_rand(1, 10);
  57. var yy = get_rand(1, 10);
  58. setInterval(function () {
  59. top += xx;
  60. left += yy;
  61. if (top > boxObj.clientHeight - nObj.offsetHeight || top < 0) {
  62. xx = -xx;
  63. }
  64. if (left > boxObj.clientWidth - nObj.offsetWidth || left < 0) {
  65. yy = -yy;
  66. }
  67. nObj.style.top = top + 'px';
  68. nObj.style.left = left + 'px';
  69. }, 50)
  70. }
  71. </script>
  72. </body>
  73. </html>

位置属性 + 动画 = 飞舞的气泡