2015-10-06 77 views
0

我正试图创建一个模拟天空中星星闪烁的效果。如何在动画完成后随机更改位置?

我把它实现在一定程度上为这样的:Fiddle

我的JS打造的明星:

var limit=50, 
body = document.body; 
spread={ 
    start:function(){ 
     for (var i=0; i<=limit; i++){ 
      var star=this.newStar(); 
      var randomD = Math.random()*30; 
      var randomDelay = randomD.toString() + "s"; 
      star.style.top=this.rand()*90+"%"; 
      star.style.left=this.rand()*98+"%"; 
      star.style.animationDelay= randomDelay; 
      body.appendChild(star); 

     }; 
    }, 
    rand:function(){ 
     return Math.random(); 
    }, 
    newStar:function(){ 
     var d = document.createElement('div'); 
     d.innerHTML= '<figure class="star"></figure>'; 
     return d.firstChild; 
    } 
}; 
spread.start(); 

但是,我想以随机的“明星”的位置,它的完成后,它的动画。

我该如何做到这一点?

+0

出于好奇,为什么你在'start'函数中同时使用'Math.random()'和wrapper' this.rand()'? – Firedrake969

回答

1

您可以在动画循环播放时触发元素上的animationiteration事件。

DEMO

spread={ 
    start:function(){ 
     for (var i=0; i<=limit; i++){ 
      var star=this.newStar(); 
      var randomD = Math.random()*30; 
      var randomDelay = randomD.toString() + "s"; 
      this.randomizeStar(star); 
      star.style.animationDelay= randomDelay; 
      star.addEventListener("animationiteration", 
        this.randomizeStar.bind(null, star)); 
      body.appendChild(star); 

     }; 
    }, 
    rand:function(){ 
     return Math.random(); 
    }, 
    newStar:function(){ 
     var d = document.createElement('div'); 
     d.innerHTML= '<figure class="star"></figure>'; 
     return d.firstChild; 
    }, 
    randomizeStar:function(star){ 
     star.style.top=Math.random()*90+"%"; 
     star.style.left=Math.random()*98+"%"; 
    } 
}; 

您将需要调整动画一点,所以在动画上opacity:0结束,但演示清楚地表明,恒星正在移动。


在你的代码的一些提示和注释:

  • 只需使用Math.random(),而不是建立在一个spread功能rand,它不会增加太多。
  • 如果你在一个Star原型中封装了星型创建和随机逻辑,代码将变得更加清晰。