test.html 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <style>
  9. img{
  10. position: absolute;
  11. }
  12. </style>
  13. </head>
  14. <body>
  15. <!-- <img src="img/1.png" alt=""> -->
  16. <script>
  17. /* 获取屏幕的宽度和高度 */
  18. var screenWidth = document.body.clientWidth || document.documentElement.clientWidth;
  19. var screenHeight = document.body.clientHeight || document.documentElement.clientHeight;
  20. /* 构造函数 属性 */
  21. function leaf(){
  22. this.width = Math.random() * 100 + 100;
  23. this.xLeft = Math.random() * (screenWidth - this.width);
  24. this.xTop = 0
  25. /*
  26. Math.random() = 0-1 随机小数 不包括1
  27. Math.random() * 4 = 0-4 随机小数 不包括4
  28. Math.random() * 4 + 1 = 1-5 随机小数 不包括5
  29. Math.floor() //向下取整 取整数
  30. Math.floor(Math.random() * 4 + 1) 向下取整 1 2 3 4
  31. */
  32. this.bg = 'img/'+ (Math.floor(Math.random() * 4 + 1)) +'.png'
  33. }
  34. /* 原型下面 写方法 */
  35. leaf.prototype.init = function(){
  36. var oImg = document.createElement('img')
  37. //引用路径
  38. oImg.src = this.bg
  39. oImg.style.width = this.width + 'px'
  40. oImg.style.left = this.xLeft + 'px'
  41. oImg.style.top = this.xTop + 'px'
  42. this.img = oImg
  43. document.body.appendChild(oImg)
  44. }
  45. leaf.prototype.fall = function(){
  46. // console.log(this)//leaf
  47. setTimeout(function(){
  48. this.timer = setInterval(function(){
  49. // console.log(this)//window
  50. if(this.img.offsetTop < screenHeight - this.img.offsetHeight){
  51. this.img.style.top = this.img.offsetTop + 10 +'px'
  52. } else {
  53. clearInterval(this.timer)
  54. }
  55. }.bind(this),20)
  56. // console.log(this)
  57. }.bind(this),Math.random()*2000)
  58. }
  59. var leafArr = []
  60. for(var i=0;i<20;i++){
  61. /* 创建实例化对象 */
  62. var leaf1 = new leaf()
  63. leafArr.push(leaf1)
  64. leaf1.init()
  65. }
  66. document.onclick = function(){
  67. for(var i=0;i<leafArr.length;i++){
  68. leafArr[i].fall()
  69. }
  70. }
  71. </script>
  72. </body>
  73. </html>