如何在jQuery中将背景颜色设置为透明? [英] How do I animate a background color to transparent in jQuery?

查看:1074
本文介绍了如何在jQuery中将背景颜色设置为透明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

透明不是真正的颜色.因此,您无法为其设置动画.通过为背景使用单独的元素并为不透明度设置动画,也许可以达到所需的效果.

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.

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在内核中不支持此功能-您需要一个插件.另请参见: jQuery + RGBA颜色动画


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

这篇关于如何在jQuery中将背景颜色设置为透明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆