6.下落的树叶.html 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. <!-- <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. // 树叶的属性
  20. // 树叶的宽度
  21. // 树叶距离顶部的位置
  22. // 树叶距离左侧的位置
  23. // 树叶图片的路径
  24. function Leaf() {
  25. this.width = Math.round(Math.random() * 100 + 100);//100-200
  26. this.top = 0;
  27. this.left = Math.random() * (screenWidth - this.width);
  28. this.newImg = './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.newImg;
  34. imgs.style.top = this.top + 'px';
  35. imgs.style.left = this.left + 'px';
  36. imgs.style.width = this.width + 'px';
  37. this.img = imgs;
  38. document.body.appendChild(imgs);
  39. }
  40. // 树叶下落
  41. Leaf.prototype.fall = function(){
  42. console.log(this)
  43. setTimeout(function() {
  44. console.log("触发",this)
  45. var timer = setInterval(function() {
  46. console.log(this,'哈哈哈')
  47. if(this.img.offsetTop < screenHeight - this.img.offsetHeight) {
  48. this.img.style.top = this.img.offsetTop + 10 +'px';
  49. } else {
  50. clearInterval(timer)
  51. }
  52. }.bind(this),20)
  53. }.bind(this),Math.random()*2000)
  54. }
  55. // 存放所有树叶
  56. let newArr = [];
  57. // 展示图片
  58. for(var i=0;i<20;i++) {
  59. var newLeaf = new Leaf();
  60. newArr.push(newLeaf);
  61. newLeaf.init();
  62. // newLeaf.fall()
  63. }
  64. // 点击树叶下落
  65. document.onclick = function() {
  66. for(var i=0;i<newArr.length;i++) {
  67. newArr[i].fall()
  68. }
  69. }
  70. // 随机数范围:Math.random()*(y-x)+x
  71. </script>
  72. </body>
  73. </html>