28.下落的树叶.html 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. <script>
  15. var screenWidth =
  16. document.body.clientWidth || document.documentElement.clientWidth;
  17. var screenHeight =
  18. document.body.clientHeight || document.documentElement.clientHeight;
  19. // 构造函数中写属性
  20. function Leaf() {
  21. // 图片的宽度
  22. this.width = Math.random() * 100 + 100; //100~200
  23. // 图片距离顶部位置
  24. this.tops = 0;
  25. // 图片距离左侧的位置
  26. this.newLeft = Math.random() * (screenWidth - this.width);
  27. // 图片的路径
  28. this.newImg = "./img/" + Math.floor(Math.random() * 4 + 1) + ".png";
  29. }
  30. //原型上写方法 初始化树叶
  31. Leaf.prototype.init = function() {
  32. // 创建标签
  33. var imgs = document.createElement("img");
  34. // 给图片路径
  35. imgs.src = this.newImg;
  36. imgs.style.width = this.width + 'px';
  37. imgs.style.top = this.tops + 'px';
  38. imgs.style.left = this.newLeft + 'px';
  39. this.img = imgs;
  40. document.body.appendChild(imgs);
  41. }
  42. // 页面展示图片
  43. var newArr = [];
  44. for(var i=0;i<20;i++) {
  45. var newLeaf = new Leaf();
  46. newArr.push(newLeaf);
  47. newLeaf.init();
  48. }
  49. // 下落树叶的方法
  50. Leaf.prototype.fall = function() {
  51. setTimeout(function(){
  52. var timer = setInterval(function(){
  53. if(this.img.offsetTop < screenHeight - this.img.offsetHeight) {
  54. this.img.style.top = this.img.offsetTop + 10 + 'px';
  55. } else {
  56. clearInterval(timer);
  57. }
  58. console.log(this)
  59. }.bind(this),20)
  60. }.bind(this)
  61. ,Math.random()*2000)
  62. }
  63. // 点击树叶下落
  64. document.onclick = function() {
  65. for(var i=0;i<newArr.length;i++) {
  66. newArr[i].fall();
  67. }
  68. }
  69. </script>
  70. </body>
  71. </html>