【问题标题】:jQuery fade background color of a header bar in when scrolled down向下滚动时,jQuery淡入标题栏的背景颜色
【发布时间】:2013-05-15 15:08:15
【问题描述】:

我正在尝试将标题的背景淡入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 Demo

感谢您的帮助

【问题讨论】:

  • 看起来你真的想为不透明度而不是背景颜色设置动画?
  • @jlbruno 我会失去我的内容的不透明度。
  • 如果您包含 jQuery UI,它就可以工作。如果您在项目中确实引用了 jQuerUI,请确保包含了效果模块。见jsfiddle.net/tJVQt/3
  • jQuery 不支持这样的动画 rgba 颜色。

标签: jquery jquery-animate


【解决方案1】:

您可以在 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 来切换类。

【讨论】:

    【解决方案2】:

    只是为了动画背景颜色的不透明度,你真的不需要颜色动画插件,你可以为较新的浏览器使用 CSS 过渡,但如果你必须支持不支持 CSS3 的浏览器,你可以使用jQuery 动画中的 step() 方法:

    $.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

    【讨论】:

      猜你喜欢
      • 2013-04-29
      • 2016-04-05
      • 2012-05-31
      • 2014-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-15
      • 2021-02-24
      相关资源
      最近更新 更多