图像在javascript方法中没有变化

时间:2013-04-08 17:36:29

标签: javascript jquery html5

我正在尝试使用jQuery交换图像但是当我运行页面时,似乎chase()方法在动画仍在进行时完成。这个想法是图像被翻转版本替换,所以他们似乎来回追逐。但是,图像在整个时间内都朝向左侧。该方法似乎一次完成,而不是显示每次迭代。

<audio controls autoplay="false" onplay="chase()">
  <source src="Links/sillyChase.mp3" type="audio/mpeg" />
</audio>
<div id="dexter">
    <img id="dex" src="Images/dexterRight.jpg" width="170" height="120"/>
</div>
<div id="deedee">
     <img id="dee" src="Images/deedeeRight.jpg" width="170" height="120"/>
</div>
</div>

<script>
function chase(){
    for(var k=0;k<10;k++){ 
        $("#dex").attr("src","Images/dexterRight.jpg"); 
        $("#dee").attr("src","Images/deedeeRight.jpg"); 

        //moves images right  
        $("#dexter").animate({"left": "+=500px"},"slow"); 
        $("#deedee").animate({"left": "+=500px"},"slow"); 

        $("#dex").attr("src","Images/dexterLeft.jpg");
        $("#dee").attr("src","Images/deedeeLeft.jpg");  

        //moves images left 
        $("#dexter").animate({"left": "-=500px"},"slow"); 
        $("#deedee").animate({"left": "-=500px"},"slow"); 
    }
}
</script>

1 个答案:

答案 0 :(得分:1)

应该工作:

function chase(){
        for(var k=0;k<10;k++){ 
             $("#dexter,#deedee").promise().done(function() {
                   $("#dex").attr("src","Images/dexterRight.jpg"); 
                   $("#dee").attr("src","Images/deedeeRight.jpg");  
              });

              //moves images right  
              $("#dexter,#deedee").animate({"left": "+=500px"},"slow", function(){
                  $("#dex").attr("src","Images/dexterLeft.jpg");
                  $("#dee").attr("src","Images/deedeeLeft.jpg");
                  $("#dexter,#deedee").animate({"left": "-=500px"},"slow");
              });
        }

    }