index.html 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. //图片宽度
  23. this.width = Math.random() * 100 + 100;
  24. //图片距离左边的距离
  25. this.xLeft = Math.random() * (screenWidth - this.width)
  26. //距离顶部
  27. this.xTop = 0
  28. //图片路径
  29. this.bg = 'img/' + Math.floor(Math.random() * 4 + 1) + '.png'
  30. /*
  31. 如何让随机数为1,2,3,4整数
  32. Math.random() 0-1随机小数
  33. Math.random() * 4 0-4随机小数
  34. Math.random() * 4 + 1 1-5之间的随机小数 不包括5
  35. Math.floor() 向下取整 跟四舍五入没关系
  36. Math.floor(Math.random() * 4 + 1) 1,2,3,4
  37. */
  38. }
  39. // 原型下面写方法
  40. leaf.prototype.init = function(){
  41. //创建img标签
  42. var oImg = document.createElement('img')
  43. //引用路径
  44. oImg.src = this.bg
  45. oImg.style.width = this.width + 'px'
  46. oImg.style.left = this.xLeft + 'px'
  47. oImg.style.top = this.xTop + 'px'
  48. this.img = oImg
  49. document.body.appendChild(oImg)
  50. }
  51. //下落的方法
  52. leaf.prototype.fall = function(){
  53. //叶子起始延迟时间
  54. setTimeout(function(){
  55. this.timer = setInterval(function(){
  56. console.log(this)
  57. if(this.img.offsetTop < screenHeight - this.img.offsetHeight){
  58. this.img.style.top = this.img.offsetTop + 10 + 'px'
  59. } else {
  60. clearInterval(this.timer)
  61. }
  62. }.bind(this),20)
  63. // console.log(this)
  64. }.bind(this),Math.random()*2000)
  65. // console.log(this)
  66. }
  67. var leafArr = []
  68. for (var i = 0; i < 20; i++) {
  69. //创建实例化对象
  70. var leaf1 = new leaf()
  71. leafArr.push(leaf1)
  72. leaf1.init()
  73. }
  74. document.onclick = function(){
  75. for(var i=0;i<leafArr.length;i++){
  76. leafArr[i].fall()
  77. }
  78. }
  79. </script>
  80. </body>
  81. </html>