博主信息
博文 7
粉丝 0
评论 0
访问量 4501
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
自动飞舞的气泡——JavaScript之DOM练习
凝思
原创
488人浏览过

自动弹出飞舞的气泡

  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() 方法按照指定的周期(以毫秒计)来调用函数或计算表达式。

批改老师:PHPzPHPz

批改状态:合格

老师批语:
本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学