javascript 如何为 div 背景的不透明度设置动画?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16254943/
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-10-27 03:55:28  来源:igfitidea点击:

How can I animate the opacity of the background of a div?

javascriptjquerycssjquery-animateopacity

提问by Gradislava Bikkulova

I have a div #test with a 0 opacity background, I want to animate it until reach the opacity of 0.7. But .animate doesn't seem to work with the css rgba.

我有一个不透明度为 0 的 div #test 背景,我想对其进行动画处理,直到达到 0.7 的不透明度。但是 .animate 似乎不适用于 css rgba。

My css is:

我的CSS是:

#test {
    background-color: rgba(0, 0, 0, 0);
}

my html:

我的 HTML:

<div id="test">
    <p>Some text</p>
    <img src="http://davidrhysthomas.co.uk/img/dexter.png" />
</div>

and my jQuery:

和我的 jQuery:

$('#test').animate({ background-color: rgba(0, 0, 0, 0.7) },1000);

Here a jsFiddle: http://jsfiddle.net/malamine_kebe/7twXW/10/

这里有一个 jsFiddle:http: //jsfiddle.net/malamine_kebe/7twXW/10/

thanks a lot for helping!

非常感谢您的帮助!

回答by Musa

First of all you need to set the property correctly

首先你需要正确设置属性

$('#test').animate({ 'background-color': 'rgba(0, 0, 0, 0.7)' },1000);

then you need to include jquery-ui to animate colours.

那么你需要包含 jquery-ui 来为颜色设置动画。

http://jsfiddle.net/7twXW/11/

http://jsfiddle.net/7twXW/11/

You can also use css transitions to animate background colours

您还可以使用 css 过渡来为背景颜色设置动画

#test {
    background-color: rgba(0, 0, 0, 0);
    -webkit-transition:background-color 1s;
    -moz-transition:background-color 1s;
    transition:background-color 1s;
}

http://jsfiddle.net/7twXW/13/

http://jsfiddle.net/7twXW/13/

回答by Ahmad

When using animate function don't use background-color but backgroundColor instead. So here is the working code :

使用 animate 函数时,不要使用 background-color 而是使用 backgroundColor。所以这是工作代码:

$('#test').animate({ backgroundColor: "rgba(0,0,0,0.7)" });