如何在 jQuery 中将背景颜色设置为透明?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/663568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:32:45  来源:igfitidea点击:

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

jqueryjquery-uitransparent

提问by

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?

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

回答by Shog9

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:

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 cananimate just the background. However, jQuery doesn't support this in core - you'll need a plugin. See also: jQuery + RGBA color animations

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

回答by Linus Gustav Larsson Thiel

I wanted to do this and since I couldn't find it, I hacked it together. This is only for white, suit to your needs:

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

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);
}

Usage:

用法:

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

回答by lucky760

$(selector)
    .css({backgroundColor:"#f00"})
    .animate({backgroundColor:"transparent"}, 2000, null, 
    function() { this.style.backgroundColor='transparent'; });

Not as clean because it fades the bg to white before making it transparent, but it's an option.

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

回答by Merlin

You can use rgba(61, 31, 17, 0.5) color where 0.5 is the opacity. Then if you want transparent set the opacity to 0.0

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

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

回答by Maarten Wolzak

I used the answer of Linus but ran into IE. Changed it about a bit to work in IE as well:

我使用了 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);
}

Usage is the same:

用法是一样的:

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

回答by Dimava

Use CSS transition:

使用 CSS 过渡:

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

or

或者

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

回答by Contra

I changed Shog9's code a bit to fit my needs. It's sort of like the jQuery UI Highlight, only it does not fade into white. It's not perfect, but it works on most elements

我稍微更改了 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); })

      );
}); }

回答by Porter

I used the function parameter to remove the style after the animation was done:

我使用函数参数在动画完成后移除样式:

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

It worked great.

它工作得很好。

回答by Ondrej Machulda

Use jQuery Color plugin: https://github.com/jquery/jquery-color

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

It will get your transparent as well as rgba animations working properly.

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

回答by Matt

You have to chain it.

你必须把它锁起来。

For example, you can't do this:

例如,你不能这样做:

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

or even

甚至

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

but you can do this:

但你可以这样做:

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