index.html 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. var screenHeight = document.body.clientHeight || document.documentElement.clientHeight
  19. //构造函数 写属性
  20. function leaf() {
  21. //图片宽度
  22. this.width = Math.random() * 100 + 100
  23. //图片位置
  24. this.xLeft = Math.random() * (screenWidth - this.width)
  25. //距离顶部
  26. this.xTop = 0
  27. //图片的路径
  28. //img/1.png
  29. this.bg = 'img/' + Math.floor(Math.random() * 4 + 1) + '.png'
  30. }
  31. //原型对象下面 写方法
  32. leaf.prototype.init = function () {
  33. //创建img标签
  34. var oImg = document.createElement('img')
  35. //赋值属性
  36. oImg.src = this.bg
  37. oImg.style.width = this.width + 'px'
  38. oImg.style.left = this.xLeft + 'px'
  39. oImg.style.top = this.xTop + 'px'
  40. document.body.appendChild(oImg)
  41. this.img = oImg
  42. }
  43. //下落的方法
  44. leaf.prototype.fall = function () {
  45. //叶子起始下落时间
  46. // console.log(this)
  47. setTimeout(function () {
  48. console.log(this)
  49. //一直下落的时间
  50. this.timer = setInterval(function () {
  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. }.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>