连续动画元素的背景

Xee*_*sHu 4 html css jquery background-color

是否可以在循环中为元素的背景颜色设置动画?

对于例如:如果我们有一个<div>拥有background-color:red并通过jQuery的我将其更改为background-color:blue.现在我想要它toggle在红色和蓝色之间连续.

我该怎么做?

Ahm*_*lfy 11

YU NO DUDE

@keyframes epilepsy {
    from {
        background: red;
        color:blue;
    }
    to {
        background: blue;
        color:red;
    }
}

.element {
    animation-duration: 0.1s;
    animation-name: epilepsy;
    animation-iteration-count: infinite;
    animation-direction: alternate;
}
Run Code Online (Sandbox Code Playgroud)

工作演示

注意:我没有添加供应商前缀

更新

如果我们可以让它在旧版浏览器上运行,那就太好了!

我有点热心,并使用jQuery和包括后备.请注意,默认情况下,jQuery animate中不支持background-color转换; jQuery的颜色插件需要

$(document).ready(function() {  
  // Using Modernizr to test if CSS transition is supported or not
  if(!Modernizr.csstransitions){
    setInterval(function() {
      // Go really crazy and do the amazing voodoo using JavaScript
      $('.default').animate({
        backgroundColor: 'red',
        color: 'blue'
      }, 100).animate({
        backgroundColor: 'blue',
        color: 'red'
      }, 100); 
    }, 100);
 });

});
Run Code Online (Sandbox Code Playgroud)

  • 很好,有用的答案. (2认同)

Ant*_*ton 6

CSS

.divClassRed{
    background-color:red;
}
.divClassBlue{
    background-color:blue;
}
Run Code Online (Sandbox Code Playgroud)

jQuery的

setInterval(function(){
    if($('#myDiv').hasClass('divClassRed')){
        $('#myDiv').addClass('divClassBlue').removeClass('divClassRed');            
    }else{
        $('#myDiv').addClass('divClassRed').removeClass('divClassBlue');
    }

},1000);
Run Code Online (Sandbox Code Playgroud)

DEMO