23.下落的树叶.html 2.0 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. }
  11. </style>
  12. </head>
  13. <body>
  14. <!-- <img src="" alt=""> -->
  15. <script>
  16. // 1.获取屏幕的宽高
  17. var screenWidth = document.body.clientWidth || document.documentElement.clientWidth;
  18. var screenHeight = document.body.clientHeight || document.documentElement.clientHeight;
  19. // 2.构造树叶属性函数
  20. function Leaf() {
  21. this.width = Math.random() * 100 + 100;
  22. this.top = 0;
  23. this.left = Math.random()*(screenWidth - this.width);
  24. this.bg = './img/' +Math.round(Math.random() * 3 + 1) + '.png';
  25. }
  26. // 3.初始化树叶
  27. Leaf.prototype.init = function() {
  28. var oImg = document.createElement('img');
  29. oImg.src = this.bg;
  30. oImg.style.width = this.width + 'px';
  31. oImg.style.top = this.top + 'px';
  32. oImg.style.left = this.left + 'px';
  33. this.img = oImg;
  34. document.body.appendChild(oImg);
  35. }
  36. // 4.点击下落树叶
  37. Leaf.prototype.fall = function() {
  38. setTimeout(function() {
  39. var timer = setInterval(function(){
  40. if(this.img.offsetTop < screenHeight - this.img.offsetHeight) {
  41. this.img.style.top = this.img.offsetTop + 10 + 'px'
  42. } else {
  43. clearInterval(timer);
  44. }
  45. }.bind(this),20)
  46. }.bind(this),Math.random()*3000);
  47. }
  48. var newList = [];
  49. for(var i=0;i<20;i++) {
  50. var leafs = new Leaf();
  51. newList.push(leafs);
  52. leafs.init();
  53. }
  54. document.onclick = function() {
  55. for(var i=0;i<newList.length;i++) {
  56. newList[i].fall();
  57. }
  58. }
  59. // new Leaf().fall()
  60. </script>
  61. </body>
  62. </html>