“stop”方法不适用于jQuery中的图像元素

时间:2014-01-19 17:45:11

标签: jquery html5

HTML:

<img src="image/heli.png"  class = "heli">

<script src="jquery/game.js" ></script>

jQuery的:

var hel = $('.heli');
fly();

function fly()
{

    hel.animate({top :'-=25px' ,left :'+=25px'},800,CollisonCheck)

}

function CollisonCheck()
{
    var tp =$(this).offset().top;
    var lft = $(this).offset().left;

    if (((tp>=365) && (tp<=610)) && ((lft>=241) && (lft<=370)))
    {
        stop_game();
    }
}

function stop_game()
{
    hel.stop();
}

运行此代码时,stop()方法无效。控制台也不会出现任何错误。

此代码中的错误是什么?如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

只有在动画完成后才会调用CollisonCheck函数,因此stop()将不执行任何操作(因为它已经停止)。你必须在某种间隔上调用``

function fly()
{
  hel.animate({top :'-=25px' ,left :'+=25px'},800)
  setInterval(CollisonCheck, 50);
}

function CollisonCheck()
{
  var tp = hel.offset().top;
  var lft = hel.offset().left;
  if (((tp>=365) && (tp<=610)) && ((lft>=241) && (lft<=370)))
  {
    stop_game();
  }
}

http://api.jquery.com/animate/

答案 1 :(得分:0)

我为我的代码找到了另一种“停止”方法的解决方案。只需写“$ fx.off = true”而不是stop()。

function stop_game()
{
$fx.off = true;
}