8.下落的树叶.html 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. /* width: 200px; */
  11. }
  12. </style>
  13. </head>
  14. <body>
  15. <!-- <img src="./img/1.png" alt=""> -->
  16. <script>
  17. var screenWidth = document.body.clientWidth || document.documentElement.clientWidth;
  18. var screenHeight = document.body.clientHeight || document.documentElement.clientHeight;
  19. function Leaf() {
  20. this.width = Math.round(Math.random() * 100 + 100);
  21. this.top = 0;
  22. this.left = Math.random() * (screenWidth - this.width);
  23. this.urls = './img/' + Math.floor(Math.random() * 4 + 1) + '.png'
  24. }
  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.left = this.left + 'px';
  31. imgs.style.top = this.top + 'px';
  32. document.body.appendChild(imgs);
  33. this.newImgs = imgs;
  34. }
  35. // 展示图片
  36. let newArr = [];
  37. for (let i = 0; i < 20; i++) {
  38. let leaf = new Leaf();
  39. leaf.init();
  40. newArr.push(leaf);
  41. }
  42. // 树叶落下
  43. Leaf.prototype.fall = function () {
  44. setTimeout(() => {
  45. var timer = setInterval(() => {
  46. if (this.newImgs.offsetTop < screenHeight - this.newImgs.offsetHeight) {
  47. this.newImgs.style.top = this.newImgs.offsetTop + 10 + 'px';
  48. } else {
  49. clearInterval(timer);
  50. }
  51. }, 20);
  52. }, Math.random() * 2000);
  53. }
  54. // 点击落下
  55. document.onclick = function () {
  56. for (let i = 0; i < newArr.length; i++) {
  57. newArr[i].fall();
  58. }
  59. }
  60. </script>
  61. </body>
  62. </html>