【问题标题】:Image rotator in JavaScript (keydown)JavaScript 中的图像旋转器(keydown)
【发布时间】:2015-03-14 11:21:47
【问题描述】:

我对 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;
        }
      });
<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>

【问题讨论】:

  • 为什么有两个body元素?如果你不知道那是什么,我建议你先阅读一些关于 HTML 和 JavaScript 的基础书籍。
  • 什么元素?你知道该怎么做吗?

标签: javascript jquery box2d keydown


【解决方案1】:

我认为问题在于 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>

【讨论】:

  • 是的,我把 keydown 放在函数之前,但是代码适用于所有文件,我不想要这个,因为我的对象(狗)是整个动画。当我按键时,我需要动画对象。
猜你喜欢
  • 2014-03-13
  • 1970-01-01
  • 1970-01-01
  • 2011-04-26
  • 1970-01-01
  • 1970-01-01
  • 2018-07-27
  • 2011-03-24
  • 1970-01-01
相关资源
最近更新 更多