1_index.html 2.3 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 = 100 + 100 * Math.random()
  24. //图片位置
  25. this.xLeft = (screenWidth - this.width) * Math.random()
  26. //距离顶部
  27. this.xTop = 0
  28. //图片路径
  29. //<img src="./img/1.png" alt="">
  30. /*
  31. Math.random() (0-1)
  32. Math.random() * 4 (0-4)
  33. Math.random() * 4 + 1 (1-5)
  34. Math.floor(Math.random() * 4 + 1) [1,2,3,4]
  35. */
  36. this.bg = 'img/' + Math.floor(Math.random() * 4 + 1) + '.png'
  37. }
  38. //原型对象下面写方法
  39. leaf.prototype.init = function () {
  40. //创建img标签
  41. var oImg = document.createElement('img')
  42. //赋值属性
  43. oImg.src = this.bg
  44. oImg.style.width = this.width + 'px'
  45. oImg.style.left = this.xLeft + 'px'
  46. oImg.style.top = this.xTop + 'px'
  47. document.body.appendChild(oImg)
  48. this.img = oImg
  49. }
  50. //下落的方法
  51. leaf.prototype.fall = function () {
  52. // console.log(this) //leaf
  53. setTimeout(function () {
  54. // console.log(this)//leaf
  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. }.bind(this), Math.random() * 2000)
  64. }
  65. var leafArr = []
  66. for (var i = 0; i < 20; i++) {
  67. //创建实例化对象
  68. var leaf1 = new leaf()
  69. leafArr.push(leaf1)
  70. leaf1.init()
  71. }
  72. document.onclick = function () {
  73. for (var i = 0; i < leafArr.length; i++) {
  74. leafArr[i].fall()
  75. }
  76. }
  77. </script>
  78. </body>
  79. </html>