Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

How do I animate a background color to transparent in jQuery?

I can animate from transparent to color, but when I tell jquery to animate the backgroundColor: 'transparent' it just changes to white. Any idea how to fix this?

question from:https://stackoverflow.com/questions/663568/how-do-i-animate-a-background-color-to-transparent-in-jquery

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Transparent isn't really a color. So, you can't animate to it. You might be able to achieve the effect you're looking for by using a separate element for the background, and animating the opacity though.

Example:

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>

Script:

// 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's comment points out that this answer is somewhat outdated - browsers do now support RGBA color values, so you can animate just the background. However, jQuery doesn't support this in core - you'll need a plugin. See also: jQuery + RGBA color animations


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...