博客列表 >飞舞的小球演示

飞舞的小球演示

赵大叔
赵大叔原创
2022年06月01日 21:54:53555浏览

html代码

  1. <html lang="en">
  2. <head>
  3. <meta charset="UTF-8">
  4. <title>Title</title>
  5. <style>
  6. #content {
  7. width:800px;
  8. height:600px;
  9. background: rgb(252, 220, 220);
  10. }
  11. </style>
  12. </head>
  13. <body>
  14. <input type="button" value="弹出球" id="btn">
  15. <div id="content">
  16. </div>
  17. <script>
  18. var content = document.getElementById('content');
  19. var colors = ['red', 'yellow', 'blue', 'green', 'yellowgreen', '#FF00FF'];
  20. document.getElementById('btn').onclick = function(){
  21. var ball = document.createElement('div');
  22. ball.style.cssText = "position:absolute;border-radius:50%;box-shadow: 0px 3px 5px #666;";
  23. var wh = Math.floor(Math.random() * 60) + 20;
  24. ball.style.width = wh + 'px';
  25. ball.style.height = wh + 'px';
  26. ball.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
  27. content.appendChild(ball);
  28. var top = content.clientHeight/2 - ball.offsetHeight/2;
  29. var left = content.clientWidth/2 - ball.offsetWidth/2;
  30. ball.style.left = left + "px";
  31. ball.style.top = top + "px";
  32. var x = Math.floor(Math.random() * 10) + 1;
  33. var y = Math.floor(Math.random() * 10) + 1;
  34. setInterval(function(){
  35. left += x;
  36. top += y;
  37. if(left < content.offsetLeft || left > (content.offsetLeft + content.offsetWidth - ball.offsetWidth)) {
  38. x = -x;
  39. }
  40. if(top < content.offsetTop || top > (content.offsetTop + content.offsetHeight - ball.offsetHeight - 3)) {
  41. y = -y;
  42. }
  43. ball.style.left = left + "px";
  44. ball.style.top = top + "px";
  45. }, 50)
  46. }
  47. </script>
  48. </body>
  49. </html>

效果展示

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议