JavaScript:嵌套循环?

3
我希望实现类似于这样的动画/序列:
动画从循环开始(想象一下一辆汽车从x1移动到x2),然后暂停1秒,再次进行动画(想象一辆汽车从x2移动到x3等等)
通过将1px添加到汽车的left值来实现汽车循环
但是我无法想象嵌套循环应该如何工作
我正在尝试仅使用setInterval完成,没有使用jquery
更新:抱歉我没有表达清楚
但假设我们有
var animation = setInterval(car_moves, 10);

我如何每两秒触发一次该动画,该动画应持续0.5秒?

这句话的意思是什么?你能解释一下吗? - Ved
如果你需要提示,可以尝试使用while循环。这将允许您运行动画,直到汽车行驶了指定的距离。 - Devin M
1
是的,但我更想看看纯JavaScript如何运作,而没有使用delay()函数。 - Francesco
足够简单,当你说x1到x2时,是指水平方向从1到2吗? - Matt Lo
我更新了我的回答,现在不需要使用jQuery就可以完成这个任务。 - chucksmash
我该如何每隔2秒触发此动画,并且动画应持续0.5秒?您可以为每2秒启动一个间隔,其中初始化您的动画间隔为10毫秒,并同时启动一个持续0.5秒的setTimeout函数来运行和清除您的动画间隔。 - Cheery
5个回答

2

看,这是使用jQuery完成的 http://jsfiddle.net/qCx69/

$('img').animate({left: '100px'}, 2000, function() {
    $(this).delay(1000).animate({left: '300px'}, 2000);
});

与之交互
<img src='http://boydstire.com/img/car_img.jpg' id='car'
     style='position:absolute;left:0px;top:100px;'>

或者没有它(这不是一个优化的解决方案) http://jsfiddle.net/8bZTA/1/

var timer = setInterval(function(){
    update_car(100,1);
}, 50);

function update_car(x,path)
{
  var car = document.getElementById('car'), 
      pos = parseInt(car.style.left) + 1;
  car.style.left = pos + 'px';
  if (pos > x)  
  {
      clearInterval(timer);
      if (path!=2)
      {
      setTimeout(function(){ //pause
       timer = setInterval(function(){update_car(200,2);}, 50);}
           , 5000);
      }
  }
}

更新:

你甚至可以创建一组停止和动作(它可以根据速度变化进行更新) http://jsfiddle.net/hFH4U/5/

var timer = setInterval(function(){update_car();}, 50);

var path = {'path1': 100, 'pause1': 2000, 'path2': 200, 
               'pause2': 2000, 'path3': 220}, 
                cur_step = 0, steps = [], speed = 1;
for (var i in path)  steps.push(i);

function update_car()
{
  var car = document.getElementById('car'), 
      pos = parseInt(car.style.left);
  if (/^path/.test(steps[cur_step]))
  {
      // motion part
      if (pos > path[steps[cur_step]])
          cur_step++;
  }
  if (/^pause/.test(steps[cur_step]))
  {
      clearTimeout(timer);
      setTimeout(function(){ 
        cur_step++;
        timer = setInterval(function(){ update_car(); }, 50);
      }, path[steps[cur_step]]);
  }
  if (cur_step >= steps.length) // end animation
      clearInterval(timer);

   car.style.left = (pos + speed) + 'px';
}

是的,但我宁愿看到纯JavaScript如何工作,而没有delay()。阅读评论... - Matt Lo
@Francesco 好的,我给你写了另一个例子。 - Cheery
这听起来接近我想要的意思...我会试一试。 - Francesco
@Francesco,请查看另一个具有不同路径步骤的示例。 - Cheery

1
演示:http://jsfiddle.net/MattLo/BVEmF/1/ 面向对象的方法:
// example showing linear movement
function car() {
   this.car = document.getElementById("car");
   this.style = this.car.style;
   this.delay = 2000; // 2 secs
   this.position = 0;
}

car.prototype.moveBy = function(m) {
   var me = this;
   setTimeout(function() {
      me.animate(m);
   },this.delay)
}

car.prototype.animate = function(m) {
   var me = this, i=0, 
   r = setInterval(function() {
      ++i;
      me._move(i);
      if(i === m) {
         me.position += i;
         // stop animation
         clearInterval(r);
         // delay again
         me.moveBy(m);
      }
   },77);
}

car.prototype._move = function(i) {
   this.style.marginLeft = i+this.position+"px";
}

Car = new car;
Car.moveBy(20);

0
你不需要嵌套循环。你可以使用类似 setInterval 的东西来实现这个目的。请记住,我正在使用 jQuery 通过 id 获取目标元素。
var interval = setInterval(IncreasePosition, 1000); // 1000 is in milliseconds
function IncreasePosition() {
    var targetElement = $("#targetElementId");
    // TODO: Get current padding value
    // TODO: Increment to it
}

该方法(IncreasePosition)将每秒调用一次并增加填充。


是的,但这样会产生突变,我想在每个像素之间保持10毫秒。 - Francesco

0

编辑:这是纯粹的JavaScript/HTML/CSS代码...你只需要一个合适的car.jpg文件...

<!DOCTYPE html>
<html>
<head>
<title>Hi</title>
<style>
#car {
    position: absolute;
    left: 0px;
}
</style>
<script type="text/javascript">
var last_x = 0;
var some_arbitrary_stopping_point = 200;
var x = self.setInterval("move()", 100);

function move() 
{
    last_x += 5;
    document.getElementById('car').style.left = last_x + 'px';
    check_pos_car();
    return last_x;
}

function check_pos_car()
{
    if (last_x > some_arbitrary_stopping_point)
    {
        x = window.clearInterval(x);
    }
}


</script>
</head>
<body>
<img src="car.jpg" id="car" alt="A beetle">
</body>
</html>

这段代码已经经过测试,可以实现你所要求的功能。当然,在move()函数中的check_pos_car()中使用if语句,你也可以不需要整个样式表来完成相同的任务。 - chucksmash

0

不要写传统的循环,你应该看一下setTimeout和setInterval。这些调用的第一个参数是一个函数,在其中你可以绘制汽车或移动汽车。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接