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

点击弹出球

程序员文章站 2022-03-03 21:55:13
...
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>html基础</title>
  5. <meta charset="UTF-8">
  6. </head>
  7. <style>
  8. *{
  9. padding: 0;
  10. margin: 0;
  11. }
  12. .box{
  13. width: 500px;
  14. height: 500px;
  15. background-color: pink;
  16. position: relative;
  17. }
  18. </style>
  19. <body>
  20. <button id="btn" onclick="fn()">弹出球</button>
  21. <div class="box" id="box">
  22. </div>
  23. </div>
  24. <script>
  25. var obox= document.getElementById('box')
  26. var colors=['red','black','white','green','yellow']
  27. function fn() {
  28. var oball= document.createElement('div')
  29. oball.style.cssText='border-radius: 50%;box-shadow: 1px 2px #666;position: absolute;background-color:red'
  30. var wh=Math.floor(Math.random()*(50-20)+20)
  31. oball.style.width=wh+'px'
  32. oball.style.height=wh+'px'
  33. oball.style.backgroundColor=colors[Math.floor(Math.random()*colors.length)]
  34. obox.appendChild(oball)
  35. var top = obox.clientHeight/2 - oball.offsetHeight/2;//?
  36. var left = obox.clientWidth/2 - oball.offsetWidth/2;//?
  37. oball.style.left=left+'px'
  38. oball.style.top=top+'px'
  39. var x=Math.floor(Math.random()*(7-2)+2)
  40. var y=Math.floor(Math.random()*(7-2)+2)
  41. setInterval(function () {
  42. left+=x
  43. top+=y
  44. if (left< obox.offsetLeft || left > (obox.offsetLeft+obox.offsetWidth-oball.offsetWidth)) {
  45. x = -x
  46. }
  47. if (top < obox.offsetTop || top > (obox.offsetTop+obox.offsetHeight-oball.offsetHeight-3)) {
  48. y = -y
  49. }
  50. oball.style.left=left+"px";
  51. oball.style.top=top+"px";
  52. }, 30)
  53. }
  54. </script>
  55. </body>
  56. </html>