2013-05-15 225 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