6.下落的树叶.html 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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: 10px;
  11. left: 100px;
  12. width: 300px; */
  13. }
  14. </style>
  15. </head>
  16. <body>
  17. <!-- <img src="./img/1.png" alt=""> -->
  18. <script>
  19. var screenWidth = document.body.clientWidth || document.documentElement.clientWidth;
  20. var screenHeight = document.body.clientHeight || document.documentElement.clientHeight;
  21. // 树叶的位置(top left width)
  22. // 树叶的属性
  23. function Leaf() {
  24. // 构造函数 this指向当前实例
  25. this.width = Math.round(Math.random() * 100 + 100);
  26. this.top = 0;
  27. this.left = Math.random() * (screenWidth - this.width);
  28. this.newUrl = './img/' + Math.floor(Math.random() * 4 + 1) + '.png'
  29. }
  30. // 绘制树叶
  31. Leaf.prototype.init = function () {
  32. var imgs = document.createElement("img");
  33. imgs.src = this.newUrl;
  34. imgs.style.width = this.width + "px";
  35. imgs.style.top = this.top + "px";
  36. imgs.style.left = this.left + "px";
  37. document.body.appendChild(imgs);
  38. this.newImg = imgs;
  39. }
  40. // 绘制多片树叶
  41. let newArr = [];
  42. for (var i = 0; i < 20; i++) {
  43. var leaf = new Leaf();
  44. newArr.push(leaf);
  45. leaf.init();
  46. }
  47. // 树叶落下
  48. Leaf.prototype.fall = function () {
  49. console.log(this)
  50. setTimeout(function () {
  51. console.log(this)
  52. var timer = setInterval(function () {
  53. // 当前元素距离顶部的大小 小于 屏幕高度-元素自身高度
  54. if (this.newImg.offsetTop < screenHeight - this.newImg.offsetHeight) {
  55. this.newImg.style.top = this.newImg.offsetTop + 10 + "px";
  56. } else {
  57. clearInterval(timer);
  58. }
  59. }.bind(this), 20)
  60. }.bind(this), Math.random() * 2000);
  61. }
  62. // 点击页面 让树叶落下
  63. document.onclick = function () {
  64. for (var i = 0; i < newArr.length; i++) {
  65. newArr[i].fall();
  66. }
  67. }
  68. </script>
  69. </body>
  70. </html>