下落的树叶.html 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. <script>
  16. //获取屏幕的宽度
  17. var screenWidth = document.body.clientWidth || document.documentElement.clientWidth
  18. //获取屏幕的高度
  19. var screenHeight = document.body.clientHeight || document.documentElement.clientHeight
  20. //构造函数 写属性
  21. function leaf(){
  22. this.width = Math.random() * 100 + 100
  23. //screenWidth - this.width 最大的距离
  24. this.xLeft = Math.random() * (screenWidth - this.width)
  25. this.xTop = 0
  26. //Math.random() 0->1 之间的随机小数
  27. //'img/1.png'
  28. // 1 - 4 随机整数
  29. //Math.random() * 4 0->4 之间的随机小数 不包括4
  30. //Math.random() * 4 + 1 1->5之间的随机小数 不包括5
  31. //Math.floor() 向下取整
  32. //Math.floor(Math.random() * 4 + 1) 1->5之间的随机小数向下取整 1 2 3 4
  33. this.bg = 'img/'+ Math.floor(Math.random() * 4 + 1) +'.png'
  34. }
  35. //原型下面 写方法
  36. //<img src="">
  37. leaf.prototype.init = function(){
  38. var oImg = document.createElement('img')
  39. oImg.src = this.bg
  40. oImg.style.width = this.width + 'px'
  41. oImg.style.left = this.xLeft + 'px'
  42. oImg.style.top = this.xTop + 'px'
  43. this.img = oImg
  44. document.body.appendChild(oImg)
  45. }
  46. //下落的方法
  47. leaf.prototype.fall = function(){
  48. setTimeout(function(){
  49. this.timer = setInterval(function(){
  50. console.log(this) //window .bind(this) this->leaf
  51. if(this.img.offsetTop < screenHeight - this.img.offsetHeight){
  52. this.img.style.top = this.img.offsetTop + 10 + 'px'
  53. } else{
  54. clearInterval(this.timer)
  55. }
  56. }.bind(this),20)
  57. // console.log(this) // window .bind(this) this-> leaf
  58. }.bind(this),Math.random()*2000)
  59. // console.log(this) // leaf
  60. }
  61. var leafArr = [];
  62. for(var i=0;i<20;i++){
  63. //创建实例化对象
  64. var leaf1 = new leaf()
  65. leaf1.init()
  66. leafArr.push(leaf1)
  67. }
  68. document.onclick = function(){
  69. for(var i=0;i<leafArr.length;i++){
  70. leafArr[i].fall()
  71. }
  72. }
  73. </script>
  74. </body>
  75. </html>