Blogger Information
Blog 7
fans 0
comment 0
visits 3289
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
自动飞舞的气泡——JavaScript之DOM练习
凝思
Original
339 people have browsed it

自动弹出飞舞的气泡

  1. <html lang="en">
  2. <head>
  3. <meta charset="UTF-8">
  4. <title>自动飞舞的气泡</title>
  5. <style>
  6. div{
  7. width:800px;
  8. height:600px;
  9. background: #ccc;
  10. }
  11. </style>
  12. </head>
  13. <body>
  14. <input type="button" size="50" value="弹出气泡" id="btn" style="width:100px;height:50px">
  15. <div id="dv"></div>
  16. <script>
  17. var button = document.getElementById("btn");
  18. setInterval(function() {
  19. button.click();
  20. },3000);//三秒自动弹出一个气泡
  21. var dv = document.getElementById('dv');
  22. var colors = ['red', 'yellow', 'blue', 'green', 'yellowgreen', 'black','white','cyan','pink','gray','violet','orange'];
  23. document.getElementById('btn').onclick=function(){
  24. var ball = document.createElement('div');
  25. ball.style.cssText="position:absolute;border-radius:50%;box-shadow: 9px 3px 5px #666;";
  26. var wh=Math.floor(Math.random()*50)+30;
  27. ball.style.width=wh+'px';
  28. ball.style.height=wh+'px';
  29. ball.style.backgroundColor=colors[Math.floor(Math.random()*colors.length)];
  30. dv.appendChild(ball);
  31. var top = dv.clientHeight/2 - ball.offsetHeight/2;
  32. var left = dv.clientWidth/2 - ball.offsetWidth/2;
  33. ball.style.left=left+"px";
  34. ball.style.top=top+"px";
  35. var x=Math.floor(Math.random()*10)+1;
  36. var y=Math.floor(Math.random()*10)+1;
  37. setInterval(function(){
  38. left+=x;
  39. top+=y;
  40. if(left < dv.offsetLeft || left > (dv.offsetLeft+dv.offsetWidth-ball.offsetWidth)) {
  41. x = -x;
  42. }
  43. if(top < dv.offsetTop || top > (dv.offsetTop+dv.offsetHeight-ball.offsetHeight-3)) {
  44. y = -y;
  45. }
  46. ball.style.left=left+"px";
  47. ball.style.top=top+"px";
  48. },30)
  49. }
  50. </script>
  51. </body>
  52. </html>

效果图

飞舞的气泡效果图

知识点小结

createElement() 方法通过指定名称创建一个元素
appendChild() 方法向节点添加最后一个子节点。
setInterval() 方法按照指定的周期(以毫秒计)来调用函数或计算表达式。

Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post