JavaScript中的图像旋转器(keydown)

时间:2015-03-14 02:51:22

标签: javascript jquery box2d keydown

我在JavaScript中遇到动画问题。我使用this link中的代码,这段代码在我的keydown函数中。但代码不起作用。来自链接的自身代码是可以的,但是在keydown的功能中无法正常工作。动画对象停留在第一个图像(dog1.PNG),下一个图像不显示。你能救我吗?



$(function() {
      $(document).keydown(function(e) {
        switch (e.keyCode) {
          case 39:

            var quotes = new Array("dog1.PNG", "gog2.PNG");
            var i = 0;

            function animation() {
              document.getElementById("dog").src = ("images/" + quotes[i]);
              if (i < 1) {
                i++;
              } else
                i = 0;

              setTimeout("animation()", 250);
            }
            animation();

            //speed objects in Box2D
            var vel = new b2Vec2(150, 0);

            game.dog.SetLinearVelocity(vel);

            break;
        }
      });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<body onLoad="animation()">
  <img src="images/dog.PNG" id="dog" />
</body>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

我认为问题在于keydown事件中的“动画”功能:范围问题

您是否按F12检查了浏览器控制台,看它在加载时是否显示任何javascript错误?

试试这个:

var i = 0 ;
function animation(){   
    document.getElementById("dog").src = ( "images/" + quotes[i] );
    if (i<1){
        i++;
    }
    else
        i = 0;

    setTimeout("animation()", 250);
} 

$(document).keydown(function(e){

    switch(e.keyCode) {
        case 39:
            var quotes = new Array ("dog1.PNG","gog2.PNG");
            animation();

            //I commented this lines because you mentioned the problem was with the animation. You can debug this later
            //speed objects in Box2D
            //var vel = new b2Vec2(150, 0);

            //game.dog.SetLinearVelocity( vel );  
        break;
}

还要确保您的Javascript插入到head部分的页面中:

<html>
    <head>
         <script>//Javascript code goes here</script>
    </head>
    <body onload=....>
        //Your html
    </body>
</html>