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

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

问题描述

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

解决方案

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

示例:

HTML:

<!-- 默认情况下,透视"到父母的背景颜色 --><div id="容器">Lorem ipsum dolor 坐 amet,consectetur adipiscing 精英.Aenean nec magna.Nulla eu mi 坐在 amet nibh pellentesque vehicula.Vivamus congue purus non purus.Nam Cursus mollis lorem.

脚本:

//加载时...$(函数(){var container = $(#container");容器.徘徊(//当光标进入时淡出背景 div,功能(){$(.background", this).stop().animate({opacity:0});},//当光标离开时淡入功能(){$(.background", this).stop().animate({opacity:1})})//允许相对于父级定位子 div.css('位置', '相对')//创建并附加背景 div//(最初可见,遮住了父母的背景).append( $("

").attr('类', '背景').css({背景颜色:'蓝色',位置:'绝对',顶部:0,左:0,zIndex:-1,宽度:容器.宽度(),高度:容器.高度()}));});


Kingjeffrey 的评论指出这个答案有些过时——浏览器现在确实支持 RGBA 颜色值,因此您可以只为背景设置动画.但是,jQuery 在核心中不支持此功能 - 您需要一个 插件.另请参阅:jQuery + RGBA 颜色动画

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.

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

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

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