2012-07-31 78 views
1

我只是在玩jQuery animate()。我試圖做出各種各樣的無限滾動背景(fiddle here)。但是對於我的生活,我無法想象一個平穩過渡。代碼張貼在這裏 -jQuery動畫 - 無限動作

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) 
    }); 
} 

什麼我要爲 - 1格移出 - 變淡什麼 - 中途淡出 - 下一個DIV淡入並再次開始循環。任何想法,我要去錯了嗎?

回答

3

不知道這是否是你們瞄準,但看看:

(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/

+1

這正是我一直在尋找。很簡約。謝謝 – 2012-07-31 10:57:42