2013-05-15 235 views
0

我試圖淡入到white的標題的背景,但當我嘗試使用一些jQuery來爲背景顏色的淡入淡出設置動畫時,它不會工作。jQuery淡入淡出的標題欄的背景顏色

jQuery的

var windw = this; 
$.fn.followTo = function (pos) { 
    var $this = this, 
     $window = $(windw); 

    $window.scroll(function(e){ 
     if ($window.scrollTop() > pos) { 
      $this.animate({'backgroundColor':'rgba(255,255,255,1)'},400); 
      console.log($this.css('backgroundColor')); 
      console.log(pos); 
     } else if ($window.scrollTop() == 0) { 
      $this.animate({'backgroundColor':'rgba(255,255,255,0)'}); 
      console.log($this.css('backgroundColor')); 
      console.log(pos + ' at the top'); 
     } else { 
      $this.animate({'backgroundColor':'rgba(255,255,255,0)'}); 
      console.log($this.css('backgroundColor')); 
     } 
    }); 
}; 

$('.home-header-main').followTo(86); 

jsFiddle Demo

幫助表示讚賞

+0

它看起來像你真的想動畫不透明度,而不是背景色? – Jeff

+0

@jlbruno我會失去我的內容的不透明度。 – ngplayground

+0

它適用於包含jQuery UI的用戶。如果您在項目中引用jQuerUI,請確保包含了效果模塊。參見http://jsfiddle.net/tJVQt/3/ – Yeronimo

回答

2

您可以使用jQuery與plugins幫助動畫RGBA,但我願意讓CSS3使用CSS轉換處理所有的這。

例子:

body { 
    background-color: rgba(255,255,255,1); 
    -webkit-transition: background-color 0.4s linear; 
     -moz-transition: background-color 0.4s linear; 
     -o-transition: background-color 0.4s linear; 
      transition: background-color 0.4s linear; 
} 

.bg-faded { 
    background-color: rgba(255,255,255,0); 
} 

然後,您可以使用JavaScript來切換類。

+0

謝謝你這個工作正常 – ngplayground

0

只是以動畫的背景顏色的透明度,你並不真的需要一個顏色動畫插件,你可以使用CSS轉換爲新的瀏覽器,但如果你有支持不支持CSS3,你可以使用瀏覽器步驟()方法在jQuery的動畫:

$.fn.followTo = function (pos) { 
    return this.each(function() { 

     var $this = $(this), 
      $window = $(window), 
      flag = true; 

     $this[0].x = 1; 

     $window.on('scroll', function(e){ 
      if ($window.scrollTop() > pos && flag) { 
       flag = !flag 
       anim($this, 0); 
      }else if ($window.scrollTop() < pos && !flag){ 
       flag = !flag 
       anim($this, 1); 
      } 

     }); 
    }); 

    function anim(elem, val) { 
     elem.stop(true, false).animate({ 
      x : val 
     }, 
     { 
      step: function(now, fx) { 
       $(fx.elem).css({backgroundColor : 'rgba(255,255,255,'+now+')'}); 
      }, 
      duration: 4000 
     }); 
    } 
}; 

$('.home-header-main').followTo(86); 

FIDDLE