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

js实现简单好玩的气泡

程序员文章站 2022-03-03 21:54:37
...

代码开始前需要先知道的几个概念


clientHeight

只读属性,元素可见的高度,不包括边框。

clientWidth

只读属性,元素可见的宽度,不包括边框。

offsetHeight

是一个只读属性,返回元素的像素高度,包含该元素的垂直内边距和边框。

offsetWidth

是一个只读属性,返回元素的像素宽度,包含该元素的水平内边距和边框。

offsetLeft

是一个只读属性,返回当前元素相对于父元素节点的左边界偏移的像素值。

offsetTop

只读属性,返回当前元素相对于其父元素的顶部的距离。

代码


  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. <style>
  7. .btn {
  8. text-align: center;
  9. }
  10. #dv {
  11. width: 800px;
  12. height: 600px;
  13. background: #eaeaea;
  14. margin: 0 auto;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div class="btn">
  20. <input type="button" value="弹出球" id="btn">
  21. <input type="button" id="stopqiu" value="暂停" />
  22. </div>
  23. <div id="dv">
  24. </div>
  25. <script>
  26. var dv = document.getElementById('dv');
  27. var colors = ['red', 'yellow', 'blue', 'green', 'pink', 'orange', 'purple', 'brown','black'];
  28. var timer;
  29. document.getElementById('stopqiu').onclick = function() {
  30. for (var i = 0; i < timer; i++) {
  31. clearInterval(i + 1)
  32. console.log(timer)
  33. }
  34. }
  35. document.getElementById('btn').onclick = function() {
  36. var ball = document.createElement('div');
  37. ball.style.cssText = "position:absolute;border-radius:50%;";
  38. var wh = Math.floor(Math.random() * 50) + 30; //向下取整,随机生成宽高度
  39. ball.style.width = wh + 'px';
  40. ball.style.height = wh + 'px';
  41. ball.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)]; //随机生成颜色
  42. dv.appendChild(ball);
  43. var dvofsetleft = dv.offsetLeft;
  44. var top = dv.clientHeight / 2 - ball.offsetHeight / 2;
  45. var left = dv.clientWidth / 2 - ball.offsetWidth / 2 + dvofsetleft;
  46. ball.style.left = left + "px";
  47. ball.style.top = top + "px";
  48. var x = Math.floor(Math.random() * 10) + 1;
  49. var y = Math.floor(Math.random() * 10) + 1;
  50. timer = setInterval(function() {
  51. left += x;
  52. top += y;
  53. if (left < dv.offsetLeft || left > (dvofsetleft + dv.offsetWidth - ball.offsetWidth)) {
  54. x = -x;
  55. }
  56. if (top < dv.offsetTop || top > (dv.offsetTop + dv.offsetHeight - ball.offsetHeight)) {
  57. y = -y;
  58. }
  59. ball.style.left = left + "px";
  60. ball.style.top = top + "px";
  61. }, 30)
  62. console.log(dv.childNodes)
  63. console.log(timer + "--------");
  64. }
  65. </script>
  66. </body>
  67. </html>

效果图

js实现简单好玩的气泡