【问题标题】:How do I animate a background color to transparent in jQuery?如何在 jQuery 中将背景颜色设置为透明?
【发布时间】:2009-03-19 19:00:54
【问题描述】:

我可以从透明动画到彩色,但是当我告诉 jquery 动画 backgroundColor: 'transparent' 时,它只会变成白色。知道如何解决这个问题吗?

【问题讨论】:

  • “透明”的问题是“看不见的绿色”看起来和“看不见的红色”一样。

标签: jquery jquery-ui transparent


【解决方案1】:

透明并不是真正的颜色。所以,你不能为它制作动画。您可以通过使用单独的背景元素并为不透明度设置动画来实现您正在寻找的效果。

示例:

HTML:

<body style="background-color:yellow">
  <!-- by default, "see through" to parent's background color -->
  <div id="container"> 
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
    Aenean nec magna. Nulla eu mi sit amet nibh pellentesque vehicula. 
    Vivamus congue purus non purus. Nam cursus mollis lorem.    
  </div>
</body>

脚本:

// on load...
$(function()
{
  var container = $("#container");
  container
    .hover(
      // fade background div out when cursor enters, 
      function() 
      { 
        $(".background", this).stop().animate({opacity:0}); 
      }, 
      // fade back in when cursor leaves
      function() 
      { 
        $(".background", this).stop().animate({opacity:1}) 
      })
    // allow positioning child div relative to parent
    .css('position', 'relative')
    // create and append background div 
    // (initially visible, obscuring parent's background)
    .append( $("<div>")
      .attr('class', 'background')
      .css({
        backgroundColor:'blue',
        position: 'absolute',
        top:0,
        left:0,
        zIndex:-1,
        width:container.width(), 
        height:container.height()
      }) 
    );
});

Kingjeffrey 的评论指出这个答案有些过时 - 浏览器现在支持 RGBA 颜色值,因此您可以只为背景设置动画。然而,jQuery 的核心并不支持这个——你需要一个plugin。另见:jQuery + RGBA color animations

【讨论】:

  • 您的说法“透明不是真正的颜色”在色彩理论中可能是正确的,但在描述浏览器如何处理“透明”关键字时并不准确。浏览器将“透明”视为黑色,不透明度为 0%。这在使用渐变时变得尤为重要。如果你在白色和透明之间创建一个 CSS3 渐变,你会看到一些灰色的蔓延(因为它会将颜色转换为黑色,将不透明度转换为 0)。为避免不必要的灰色,请将白色渐变设置为 rgba(255,255,255,0)。
【解决方案2】:

我想这样做,但因为我找不到它,所以我一起破解了它。这仅适用于白色,适合您的需求:

function animate_bg(ele, from, to) {
    ele.css("background-color", "rgba(255, 255, 255, " + (from += from > to ? -1 : 1) / 10 + ")"); 
    if(from != to)  
        setTimeout(function() { animate_bg(ele, from, to) }, 20);
}

用法:

$("a").hover(
    function() {return animate_bg($(this), 0, 10)},
    function() {return animate_bg($(this), 10, 0)}
);

【讨论】:

  • 为什么要除以 10,而不遵守从 0 到 1 的透明度 CSS 标准?
【解决方案3】:
$(selector)
    .css({backgroundColor:"#f00"})
    .animate({backgroundColor:"transparent"}, 2000, null, 
    function() { this.style.backgroundColor='transparent'; });

不那么干净,因为它会在使背景透明之前将背景淡化为白色,但这是一种选择。

【讨论】:

  • 你把它变成红色,而不是白色。
【解决方案4】:

您可以使用 rgba(61, 31, 17, 0.5) 颜色,其中 0.5 是不透明度。 然后如果你想透明设置不透明度为 0.0

$('.myClass').animate({ "backgroundColor" : "rgba(61, 31, 17, 0.0)" }, 1000);

【讨论】:

  • 如果起始颜色的不透明度已经有所降低(例如,CSS 中默认为 rgba(255,255,255,.2),则速度会停留在此不透明度上,并且 rgba 不会改变任何内容
  • 这就是答案,简单明了。 jQuery .animate 函数正是具有这样的目的,考虑到它用于“执行一组 CSS 属性的自定义动画”,在当前情况下,在 background-color 上。
  • 你还应该提到你需要一个额外的 jquery 插件:github.com/jquery/jquery-color
【解决方案5】:

我使用了Linus的答案,但遇到了IE。稍微改动了一下,也可以在 IE 中使用:

function animate_bg(ele, from, to) {
    from += from > to ? -1 : 1;
    if(!$.support.opacity){
        if(from != to){
            var opStr = (Math.round(from * 25.5)).toString(16);
            //alert(opStr)
            ele.css({background:'transparent',filter:"progid:DXImageTransform.Microsoft.gradient(startColorstr=#" + opStr + "FFFF00, endColorstr=#" + opStr + "FFFF00)"});   
        }else{
            ele.css({background:'transparent',filter:"none"});   
        }
    }else{
        ele.css("backgroundColor", "rgba(255, 255, 0, " + (from) / 10 + ")"); 
    }

    if(from != to)  
        setTimeout(function() { animate_bg(ele, from, to) }, 50);
}

用法同理:

$("a").hover(
    function() {return animate_bg($(this), 0, 10)},
    function() {return animate_bg($(this), 10, 0)}
);

【讨论】:

    【解决方案6】:

    使用 CSS 过渡:

    $('smth').css('transition','background-color 1s').css('background-color','transparent')
    

    $('h1').css({'transition':'background-color 1s','background-color':'red'})
    

    【讨论】:

      【解决方案7】:

      我稍微更改了 Shog9 的代码以满足我的需要。 它有点像 jQuery UI Highlight,只是它不会变成白色。 它并不完美,但它适用于大多数元素

      function highlight(element, color, speed) {
      if (speed == null) speed = "fast";
      var e;
      var position;
      element.each(function() {
          e = $(this);
          position = e.css('position');
          if (position != 'absolute')
              e.css('position', 'relative');
          log(position);
          e.append($("<div>")
              .css({
                  backgroundColor: color,
                  position: 'absolute',
                  top: 0,
                  left: 0,
                  zIndex: -1,
                  display: "none",
                  width: e.width(),
                  height: e.height()
              }).fadeIn(speed).fadeOut(speed, function() { $(this).remove(); e.css('position', position); })
      
            );
      }); }
      

      【讨论】:

        【解决方案8】:

        动画完成后我用函数参数去掉了样式:

        $('[orgID=' + orgID + 'bg]').animate({ backgroundColor: "white" }, 300, "linear", function()
         {
             $('[orgID=' + orgID + 'bg]').css('background-color', '');
        });
        

        效果很好。

        【讨论】:

          【解决方案9】:

          使用 jQuery Color 插件:https://github.com/jquery/jquery-color

          它将使您的透明动画和 rgba 动画正常工作。

          【讨论】:

            【解决方案10】:

            你必须把它锁起来。

            例如,你不能这样做:

            $('#panel').animate({'backgroundColor' : 'rgba(255,255,0,0.7', 'opacity': 1}, 3000);
            

            甚至

            $('#panel').animate({'background-color' : 'yellow', 'opacity': 1}, 3000);
            

            但你可以这样做:

            $('#panel').css('background-color', 'rgba(255,255,0,0.7)').animate({'opacity': 1}, 3000);
            

            【讨论】:

              【解决方案11】:

              我的解决方案是动画到用户看到的颜色(即父元素的颜色),然后在动画完成后设置为原始颜色(可能是也可能不是“透明”)

              var $t = $(some selector);
              
              var seenColour = findColour($t, 'background-color');
              var origColour = $t.css('background-color');
              $t.css('background-color', '#ffff99');
              $t.animate(
                  {backgroundColor: seenColour}, 
                  4000, 
                  function(){ $t.css('background-color', origColour)}
              );
              
              function findColour($elem, colourAttr)
              {
                  var colour = $elem.css(colourAttr);
                  if (colour === 'transparent')
                  {
                      var $parent = $elem.parent();
                      if ($parent)
                      {
                          return findColour($parent, colourAttr);
                      }
                      // Default to white
                      return '#FFFFFF'; 
                  }
                  return colour;
              }
              

              【讨论】:

                【解决方案12】:

                使用背景代替背景颜色:

                $('#myDiv').animate({background: "transparent"});
                

                【讨论】:

                  猜你喜欢
                  • 2020-03-03
                  • 2015-07-10
                  • 2016-11-06
                  • 1970-01-01
                  • 2011-04-14
                  • 2020-07-21
                  • 2011-02-11
                  • 2017-06-02
                  • 1970-01-01
                  相关资源
                  最近更新 更多