10.下落的树叶.html 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. /* top: 0; */
  11. }
  12. </style>
  13. </head>
  14. <body>
  15. <script>
  16. const screenWidth = document.documentElement.clientWidth || document.body.clientWidth;
  17. const screenHeight = document.documentElement.clientHeight || document.body.clientHeight;
  18. function Leaf() {
  19. // 宽度
  20. this.width = Math.round(Math.random() * 100 + 100);
  21. // 距离
  22. this.top = 0;
  23. this.left = Math.random() * (screenWidth - this.width);
  24. this.urls = './img/' + Math.floor(Math.random() * 4 + 1) + '.png'
  25. }
  26. Leaf.prototype.init = function () {
  27. var imgs = document.createElement("img");
  28. imgs.src = this.urls;
  29. imgs.style.width = this.width + 'px';
  30. imgs.style.top = this.top;
  31. imgs.style.left = this.left + 'px';
  32. document.body.appendChild(imgs);
  33. this.newImgs = imgs;
  34. }
  35. let newArr = [];
  36. for (let i = 0; i < 20; i++) {
  37. let leaf = new Leaf();
  38. leaf.init();
  39. newArr.push(leaf)
  40. }
  41. Leaf.prototype.fail = function () {
  42. setTimeout(() => {
  43. var timer = setInterval(() => {
  44. if (this.newImgs.offsetTop < screenHeight - this.newImgs.offsetHeight) {
  45. this.newImgs.style.top = this.newImgs.offsetTop + 10 + 'px';
  46. } else {
  47. clearInterval(timer);
  48. }
  49. }, 20)
  50. }, Math.random() * 2000)
  51. }
  52. document.onclick = function () {
  53. for (let i = 0; i < newArr.length; i++) {
  54. newArr[i].fail();
  55. }
  56. }
  57. </script>
  58. </body>
  59. </html>