Jak*_*ake 4 jquery gradient background jquery-animate
我正在尝试用jQuery构建一个背景动画,它从一个渐变变为另一个渐变.我知道你可以使用.animate()函数来改变纯色背景颜色,但这也可以用于渐变吗?
这是一些旧的Digg风格评论的好例子.我正在寻找这样的动画,从绿色到黄色

使用jQuery动画背景绝对是可行的,如本CodePen所示(不是我的创作,但非常光滑):http://codepen.io/quasimondo/pen/lDdrF
CodePen示例使用一些光滑的位移和其他技巧来确定颜色,但他只定义了一个函数(updateGradient),它修改了背景的CSS,然后将其包装在setInterval中.
updateGradient的主要内容如下:
$('#gradient').css({
background: "-webkit-gradient(linear, left top, right top, from("+color1+"),
to("+color2+"))"}).css({
background: "-moz-linear-gradient(left, "+color1+" 0%, "+color2+" 100%)"});
Run Code Online (Sandbox Code Playgroud)
然后动态设置颜色变量,你就是肉汁.
更新:如今,所有主流浏览器都支持 CSS 动画,这比 jQuery 更可靠。作为参考,请参阅罗希特的回答。
旧答案:
使用 jQuery 直接对背景进行动画处理几乎是不可能的,至少我想不出办法。不过有一个办法:
-webkit-transition: background 5s ;
-moz-transition: background 5s ;
-ms-transition: background 5s ;
-o-transition: background 5s ;
transition: background 5s ;
Run Code Online (Sandbox Code Playgroud)
这确保了过渡的存在。例如,您可以在 CSS 中执行此操作:
.background_animation_element{
-webkit-transition: background 5s ;
-moz-transition: background 5s ;
-ms-transition: background 5s ;
-o-transition: background 5s ;
transition: background 5s ;
background: rgb(71,234,46);
background: -moz-linear-gradient(top, rgba(71,234,46,1) 0%, rgba(63,63,63,1) 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(71,234,46,1)), color-stop(100%,rgba(63,63,63,1)));
background: -webkit-linear-gradient(top, rgba(71,234,46,1) 0%,rgba(63,63,63,1) 100%);
background: -o-linear-gradient(top, rgba(71,234,46,1) 0%,rgba(63,63,63,1) 100%);
background: -ms-linear-gradient(top, rgba(71,234,46,1) 0%,rgba(63,63,63,1) 100%);
background: linear-gradient(top, rgba(71,234,46,1) 0%,rgba(63,63,63,1) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#47ea2e', endColorstr='#3f3f3f',GradientType=0 );
}
.background_animation_element.yellow{
background: rgb(247,247,49);
background: -moz-linear-gradient(top, rgba(247,247,49,1) 0%, rgba(63,63,63,1) 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(247,247,49,1)), color-stop(100%,rgba(63,63,63,1)));
background: -webkit-linear-gradient(top, rgba(247,247,49,1) 0%,rgba(63,63,63,1) 100%);
background: -o-linear-gradient(top, rgba(247,247,49,1) 0%,rgba(63,63,63,1) 100%);
background: -ms-linear-gradient(top, rgba(247,247,49,1) 0%,rgba(63,63,63,1) 100%);
background: linear-gradient(top, rgba(247,247,49,1) 0%,rgba(63,63,63,1) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f7f731', endColorstr='#3f3f3f',GradientType=0 );
}
Run Code Online (Sandbox Code Playgroud)
并且,使用 jQuery 添加或删除黄色类:
$('.background_animation_element').addClass('yellow');
Run Code Online (Sandbox Code Playgroud)
由于 CSS 文件中的过渡持续时间属性,这将确保逐渐过渡。