21.下落的树叶.html 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. </head>
  8. <body>
  9. <style>
  10. img {
  11. position: absolute;
  12. }
  13. </style>
  14. <script>
  15. // scrollTop scrollLeft
  16. // 1.获取屏幕可视宽高
  17. var screenWidth = document.documentElement.clientWidth || document.body.clientWidth;
  18. var screenHeight = document.documentElement.clientHeight || document.body.clientHeight;
  19. console.log(screenWidth,screenHeight)
  20. // 2.构造函数属性
  21. function Leaf() {
  22. // 定义图片宽度
  23. this.width = Math.round(Math.random() * 100 + 100);
  24. // 图片距离顶部位置
  25. this.tops = 0;
  26. // 图片距离左侧位置
  27. this.newLeft = Math.random() * (screenWidth - this.width);
  28. // 图片引入 ./img/3.png
  29. // Math.random()* y-x + x
  30. // Math.round(Math.random() * 3 + 1)
  31. this.newImg = "./img/" + Math.floor(Math.random() * 4 + 1) + '.png'
  32. }
  33. // new Leaf();
  34. Leaf.prototype.init = function() {
  35. // 创建图片标签
  36. var imgs = document.createElement("img");
  37. // 图片路径
  38. imgs.src = this.newImg;
  39. // 图片距离顶部位置
  40. imgs.style.top = this.tops + "px";
  41. // 图片距离左侧位置
  42. imgs.style.left = this.newLeft + "px";
  43. // 图片宽度
  44. imgs.style.width = this.width + "px";
  45. this.img = imgs;
  46. // console.log(this.img)
  47. document.body.appendChild(imgs);
  48. }
  49. //页面渲染树叶
  50. var newArr = [];
  51. for(var i = 0; i <20;i++) {
  52. var newLeaf = new Leaf();
  53. newLeaf.init();
  54. newArr.push(newLeaf);
  55. }
  56. // 树叶下落
  57. // 箭头函数
  58. // 没有this指向 this当前项
  59. Leaf.prototype.fail = function() {
  60. setTimeout(function(){
  61. var timer = setInterval(function(){
  62. if(this.img.offsetTop < screenHeight - this.img.offsetHeight){
  63. this.img.style.top = this.img.offsetTop + 10 + 'px';
  64. } else {
  65. clearInterval(timer)
  66. }
  67. }.bind(this),30);
  68. }.bind(this),Math.random()*3000)
  69. }
  70. // 点击图片树叶下落
  71. document.onclick = function() {
  72. for(var i=0;i<newArr.length;i++) {
  73. newArr[i].fail();
  74. }
  75. }
  76. </script>
  77. </body>
  78. </html>