【问题标题】:Repeat function after callback without delay (Jquery)无延迟回调后重复功能(Jquery)
【发布时间】:2016-02-02 01:20:22
【问题描述】:

所以我在我的网站上制作了这个幻灯片。现在它将屏幕外的所有图片向左移动,将第一项附加到容器的末尾,然后重复。问题是我必须设置一个大于动画时间的计时器,否则它会每隔一段时间为错误的元素设置动画。当 appendTo 函数完成时,我怎样才能让它重复而不会有延迟?

它的样子:https://gyazo.com/04b427117ee9d01f65fcdba790ec0730

Javascript:

$(function(){
setInterval(function(){
    var p = $(".photo-grid-slideshow .photo-crop").css('width');
    $(".photo-grid-slideshow .photo-crop:first-of-type").animate({marginLeft: '-=' + p}, 3000, "linear", function(){
        $(this).css("margin-left", 0).appendTo('.photo-grid-slideshow');
    })
}, 3500);
});

【问题讨论】:

  • 您应该在此处或jsfiddle.net 上添加工作代码sn-p。

标签: javascript jquery


【解决方案1】:

.appendTo 之后再次运行它:

$(function(){
  function animate(){
      var p = $(".photo-grid-slideshow .photo-crop").css('width');
      $(".photo-grid-slideshow .photo-crop:first-of-type").animate({marginLeft: '-=' + p}, 3000, "linear", function(){
        $(this).css("margin-left", 0).appendTo('.photo-grid-slideshow');
        animate(); // here we call it again
    })
  }
  animate(); // start animation
})

【讨论】:

  • 如果你走这条路,你只需要在尝试动画之前确保元素存在var $elem = $(".photo-grid-slideshow .photo-crop:first-of-type"); if($elem.length){ $elem.animate(...
  • 谢谢!像魅力一样工作:)
【解决方案2】:

对于像这样的你想要链接动画的用例,使用像 GreenSock 这样的库可能真的很有帮助。一个额外的好处是动画将比使用 jQuery 的原生动画功能更流畅和更可定制。

至于您当前的实现,如果您在脚本中包含 HTML 和 CSS 的 sn-p,则提供帮助会更容易。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-02
    • 1970-01-01
    • 2017-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多