javascript - jQuery 动画 - 无限运动

标签 javascript jquery jquery-animate

我只是在玩jQuery animate() .我试图制作各种无限滚动背景(fiddle here)。但是对于我的生活,我无法找到平稳的过渡。代码张贴在这里 -

HTML

<div class='bg r hide'></div>
<div class='bg g hide'></div>
<div class='bg y hide'></div>
<div class='bg b hide'></div>

JavaScript

var backgroundTimeout = 1700;

function animateMotion(){
    $('.bg').each(function(i, item) {
        var self = $(this);
        setTimeout(function() {
            self.css('opacity', '0.5').removeClass('hide')
                .animate({opacity: 1, marginLeft: '+=6'}, backgroundTimeout / 3)
                .animate({
                    marginLeft: '+=30',
                    opacity: 0,
                    queue: false,
                }, backgroundTimeout + 400, 'linear', function() {
                    self.css('marginLeft', 0);
                    self.css('opacity', 1);
                    self.addClass('hide');
                })
                if (self.index() === $('.bg').length - 1) {
                    setTimeout(animateMotion, backgroundTimeout);
                }
        }, backgroundTimeout * i + 1)
    });
}

我要做什么 - 第一个 div 移出 - 淡出到无 - 淡出中途 - 下一个 div 淡入并再次开始循环。我哪里出错了?

最佳答案

不确定这是否是您的目标,但请看一下:

(function loop(idx) {
  var
    $elements = $('#wrapper div'),
    idx = idx % $elements.length;

  $elements.eq(idx).css({
    opacity: 0,
    left: 0
  }).removeClass('hide').show().animate({
    opacity: 1,
    left: 30
  }, {
    duration: 1000,
    easing: 'linear',
    complete: function () {
      $(this).animate({
        opacity: 0,
        left: 60
      }, {
        duration: 1000,
        easing: 'linear',
        complete: function () {
          $(this).addClass('hide');
        }
      });

      loop(idx + 1);
    }
  });
}(0));

与:

<div id="wrapper">
  <div class='bg r hide'></div>
  <div class='bg g hide'></div>
  <div class='bg y hide'></div>
  <div class='bg b hide'></div>
</div>

演示:http://jsfiddle.net/hbh7z/1/

关于javascript - jQuery 动画 - 无限运动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11737523/

相关文章:

javascript - 在 ajax 响应中返回 false 不起作用,并且表单不会取消提交

javascript - 使用 ZombieJS 从异步点击事件触发的 Ajax 获取 Http 错误

javascript - 单击 iframe 嵌入 map 时启用指针事件

Javascript - 无法从嵌套函数访问本地范围对象

javascript - 使用 Canvas 为圆环图中的线条设置动画

jquery - 我们可以像 CSS3 一样在 jQuery 中使用类转换吗?

对象的 Javascript oop 实例

javascript - 检查条件后使用 jQuery 取消选中框

javascript - 全屏滑动div不同大小和方向

JQuery 滑动 2 个 div