0

我正在尝试将标题的背景淡入,white但是当我尝试使用一些 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 演示

帮助表示赞赏

4

2 回答 2

2

你可以在plugins的帮助下使用 jQuery 为 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 来切换类。

于 2013-05-15T15:16:16.710 回答
0

只是为了对背景颜色的不透明度进行动画处理,您实际上并不需要颜色动画插件,您可以为较新的浏览器使用 CSS 过渡,但如果您必须支持不支持 CSS3 的浏览器,您可以使用 step() 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);

小提琴

于 2013-05-15T15:22:52.633 回答