JavaScript 中的图像旋转器(键下)

Image rotator in JavaScript (keydown)

本文关键字:键下 旋转 图像 JavaScript      更新时间:2023-09-26

我在JavaScript中遇到动画问题。我使用此链接中的代码,并且此代码在我的函数中用于键控。但是代码不起作用。链接本身的代码是可以的,但在带有键控的功能中无法正常工作。动画对象保留在第一个图像 (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;
        }
      });
<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>

我认为问题在于函数"animation"位于键下事件中: 范围问题

您是否检查过按 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>