随机气泡案例

最近一直在学习框架,原生js方法及使用忘记的差不多了,温习一下
话不多说直接代码


  
  
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title> </title>
  6. <style>
  7. * {
  8. margin: 0;
  9. padding: 0;
  10. }
  11. body {
  12. overflow: hidden;
  13. /*溢出隐藏*/
  14. /*解决塌陷*/
  15. /*清除浮动*/
  16. }
  17. div{
  18. position: absolute;
  19. border-radius: 50%;
  20. }
  21. </style>
  22. </head>
  23. <body>
  24. <!--生成100个小圆,大小随机,位置随机,颜色随机,透明度随机-->
  25. <!--让圆闪烁起来-->
  26. </body>
  27. <script>
  28. for ( var i= 0; i< 40; i++) {
  29. var d = document.createElement( "div");
  30. var cm = rand( 10, 150);
  31. d.style.width = cm + 'px';
  32. d.style.height = cm + 'px';
  33. d.style.left = rand( 0, window.innerWidth -150) + 'px';
  34. d.style.top = rand( 0, window.innerHeight -150) + 'px';
  35. var r = rand( 0, 255);
  36. var g = rand( 0, 255);
  37. var b = rand( 0, 255);
  38. var color = `rgb(${r},${g},${b})`;
  39. d.style.backgroundColor = color;
  40. var op = Math.random();
  41. d.style.opacity = op;
  42. // 手动为div创造一个属性speed
  43. d.speedOpacity = 0.01;
  44. if ( 0.5 - Math.random() > 0) {
  45. d.speedOpacity = -0.01;
  46. }
  47. d.speedX = rand( 2, 4);
  48. if ( 0.5 - Math.random() > 0) {
  49. d.speedX *= -1;
  50. }
  51. d.speedY = rand( 2, 4);
  52. if ( 0.5 - Math.random() > 0) {
  53. d.speedY *= -1;
  54. }
  55. document.body.appendChild(d);
  56. }
  57. function rand(min,max) {
  58. return Math.round( Math.random() * (max-min) + min);
  59. }
  60. function changeOpacityAndPosition() {
  61. var ds = document.getElementsByTagName( "div");
  62. for ( var i= 0; i<ds.length; i++) {
  63. var d = ds[i];
  64. var op = d.style.opacity;
  65. op = parseFloat(op);
  66. op += d.speedOpacity;
  67. if (op>= 1 || op <= 0) {
  68. d.speedOpacity *= -1;
  69. }
  70. d.style.opacity = op;
  71. var x = d.offsetLeft + d.speedX;
  72. var y = d.offsetTop + d.speedY;
  73. if (x < 0) {
  74. x = 0;
  75. d.speedX *= -1;
  76. } else if (x > window.innerWidth-d.offsetWidth) {
  77. x = window.innerWidth-d.offsetWidth;
  78. d.speedX *= -1;
  79. }
  80. if (y < 0) {
  81. y = 0;
  82. d.speedY *= -1;
  83. } else if (y > window.innerHeight-d.offsetHeight) {
  84. y = window.innerHeight-d.offsetHeight;
  85. d.speedY *= -1;
  86. }
  87. d.style.left = x + 'px';
  88. d.style.top = y + 'px';
  89. }
  90. }
  91. setInterval( function(){
  92. changeOpacityAndPosition()
  93. }, 30);
  94. </script>
  95. </html>
  96. <!--relative:不会影响元素本身的特性,定位参考是原来的位置
  97. absolute: 脱离文档流,找最近的使用了定位的父级来定位,如果没有找body
  98. fixed: 脱离文档流,找窗口定位-->

可以通过改变i的值来改变气泡个数。目前定义的是40

效果:

个人觉得挺好看的,电脑闲置的时候可以把整个网页打开,然后F11全屏,作为桌面背景。

还有,由于是网页所以不能直接做成桌面背景,有人说可以截图,截成视频,拜托这些完全是随机的,弄成视频就不是随机的了好吧-_-!。当然如果你有什么办法把网页做成桌面背景,欢迎给我留言。

还有本次代码是本校实训时的成果,并不是完全靠个人做出来的。如有雷同,不胜惶恐!

转载自:https://blog.csdn.net/Lee_1310/article/details/89048898

猜你喜欢

转载自blog.csdn.net/weixin_44392027/article/details/89350202