25.下落的树叶.html 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. <!-- <a href=""></a> -->
  15. <!-- <img src="./img/1.png" alt=""> -->
  16. <script>
  17. var screenWidth = document.documentElement.clientWidth || document.body.clientWidth;
  18. var screenHeight = document.documentElement.clientHeight || document.body.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. Leaf.prototype.init = function () {
  26. var imgs = document.createElement("img");
  27. imgs.src = this.urls;
  28. imgs.style.width = this.width + 'px';
  29. imgs.style.top = this.top;
  30. imgs.style.left = this.left + 'px';
  31. document.body.appendChild(imgs);
  32. this.newImg = imgs;
  33. }
  34. var newArr = [];
  35. for (var i = 0; i < 20; i++) {
  36. var leaf = new Leaf();
  37. newArr.push(leaf);
  38. leaf.init()
  39. }
  40. Leaf.prototype.fall = function () {
  41. setTimeout(function () {
  42. var timer = setInterval(function () {
  43. if (this.newImg.offsetTop < screenHeight - this.newImg.offsetHeight) {
  44. this.newImg.style.top = this.newImg.offsetTop + 10 + 'px';
  45. } else {
  46. clearInterval(timer)
  47. }
  48. }.bind(this), 20);
  49. }.bind(this), Math.random()*2000);
  50. }
  51. document.onclick = function () {
  52. for (var i = 0; i < newArr.length; i++) {
  53. newArr[i].fall()
  54. }
  55. }
  56. </script>
  57. </body>
  58. </html>