perhaps? 2016-06-11 12:36 采纳率: 100%
浏览 16

使用Javascript进行图像动画

Why the timeout don't work? If i work without the function sleep, they return to me an undefined data.. With this function they work but without sleeping time, they go directly to the last image.. :-/

    function sleep(value, data, i) {
        document.getElementById(value).src = data[i];
    }

function imgAnimation(value){
    var img = document.getElementById(value).src;
    $.ajax({
    type: "POST",
    url: "static/cercaThumbs.php",
    data: 'id=' + value,
    datatype: 'json',
    success: function (data) {
        var elements = Object.keys(data).length;
        for (var i = 0; i < elements; i++) {
                if(i == elements){i = 0;}
                setTimeout(sleep(value, data, i), 300);
        }
    }
});
}
  • 写回答

2条回答 默认 最新

  • weixin_33739523 2016-06-11 12:40
    关注

    You need to pass a function to setTimeout. You're calling the function sleep and passing its result.

    setTimeout(function() {
      sleep(value, data, i);
    }, 300);
    

    But it still won't work, because you're setting a bunch of timeouts at the same time, so they'll all trigger 300ms later at the same time. To animate you might try something like:

    var data = [
      'https://cdnjs.cloudflare.com/ajax/libs/emojione/2.2.2/assets/png/0030.png',
      'https://cdnjs.cloudflare.com/ajax/libs/emojione/2.2.2/assets/png/0031.png',
      'https://cdnjs.cloudflare.com/ajax/libs/emojione/2.2.2/assets/png/0032.png',
    ]
    var frame = 0;
    var elements = data.length;
    var animation = setInterval(function() {
      frame = (frame + 1) % elements;
      document.getElementById('test').src = data[frame];
    }, 300);
    <img id=test>

    This sets up a single repeating callback which can advance to the next frame each time. In the example above it will loop forever, or you can call clearInterval(animation) once you're finished.

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏