6.下落的树叶.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // 获取屏幕宽高
  2. var screenWidth = document.documentElement.clientWidth || document.body.clientWidth;
  3. var screenHeight = document.documentElement.clientHeight || document.body.clientHeight;
  4. // 构造函数写属性
  5. function leaf() {
  6. // 图片的宽度
  7. this.width = Math.random() * 100 + 100;
  8. // 图片距离左侧的距离
  9. this.newLeft = Math.random() * (screenWidth - this.width);
  10. // 距离顶部位置
  11. this.tops = 0;
  12. // 图片路径的展示
  13. this.newImg = '../img/' + Math.floor(Math.random() * 4 + 1) + '.png'
  14. }
  15. // 原型上写方法
  16. // 树叶初始状态方法
  17. leaf.prototype.init = function() {
  18. // 创建标签
  19. var imgs = document.createElement("img");
  20. // imgs元素添加路径
  21. imgs.src = this.newImg;
  22. imgs.style.width = this.width + 'px';
  23. imgs.style.left = this.newLeft + 'px';
  24. imgs.style.top = this.tops + 'px';
  25. this.img = imgs;
  26. document.body.appendChild(imgs);
  27. }
  28. // 树叶落下方法
  29. leaf.prototype.fall = function() {
  30. setTimeout(function(){
  31. this.timer = setInterval(function(){
  32. if(this.img.offsetTop < screenHeight - this.img.offsetHeight) {
  33. this.img.style.top = this.img.offsetTop + 10 + 'px';
  34. } else {
  35. clearInterval(this.timer)
  36. }
  37. }.bind(this),20)
  38. }.bind(this),Math.random()*2000)
  39. }
  40. var newArr = [];
  41. for(var i=0; i<30; i++) {
  42. var leaf1 = new leaf();
  43. newArr.push(leaf1);
  44. leaf1.init();
  45. }
  46. // document.onclick = function() {
  47. // for(var i=0;i<newArr.length;i++) {
  48. // newArr[i].fall();
  49. // }
  50. // }