24.下落的树叶.html 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>Document</title>
  7. <style>
  8. img {
  9. position: absolute;
  10. }
  11. </style>
  12. </head>
  13. <body>
  14. <script>
  15. var screenWidth =
  16. document.documentElement.clientWidth || document.body.clientWidth;
  17. var screenHeight =
  18. document.documentElement.clientHeight || document.body.clientHeight;
  19. function Leaf() {
  20. // 图片的宽度
  21. this.width1 = Math.random() * 100 + 100;
  22. // 距离顶部的位置
  23. this.top1 = 0;
  24. // 距离左侧的位置
  25. this.left1 = Math.random() * (screenWidth - this.width1);
  26. // 图片的路径
  27. this.img1 = "./img/" + Math.floor(Math.random() * 4 + 1) + ".png";
  28. }
  29. Leaf.prototype.init = function () {
  30. var imgs = document.createElement("img");
  31. imgs.style.width = this.width1 + "px";
  32. imgs.src = this.img1;
  33. imgs.style.left = this.left1 + "px";
  34. imgs.style.top = this.top + "px";
  35. this.myImg = imgs;
  36. document.body.appendChild(imgs);
  37. };
  38. var failList = []
  39. for (var i = 0; i < 20; i++) {
  40. var newLeaf = new Leaf();
  41. failList.push(newLeaf)
  42. newLeaf.init();
  43. }
  44. Leaf.prototype.fail = function () {
  45. // console
  46. setTimeout(
  47. function () {
  48. var timer = setInterval(
  49. function () {
  50. if (
  51. this.myImg.offsetTop <
  52. screenHeight - this.myImg.offsetHeight
  53. ) {
  54. this.myImg.style.top = this.myImg.offsetTop + 10 + "px";
  55. } else {
  56. clearInterval(timer);
  57. }
  58. }.bind(this),
  59. 20
  60. );
  61. }.bind(this),
  62. Math.random()*3000
  63. );
  64. };
  65. document.onclick = function () {
  66. for(var i=0;i<failList.length;i++) {
  67. failList[i].fail()
  68. }
  69. };
  70. </script>
  71. </body>
  72. </html>