缓慢变色的背景

时间:2014-08-27 12:21:18

标签: javascript jquery

我需要在网站上做一个慢慢改变颜色的背景,所以不断从红色,绿色到蓝色,再到红色。有没有办法用jQuery或JavaScript来做到这一点? 感谢

2 个答案:

答案 0 :(得分:2)

对于简单的动画,您可以使用CSS:

body {
  background-color: red;
  -webkit-animation:  changeBgColor 3s infinite;
  -moz-animation:     changeBgColor 3s infinite;
  -ms-animation:      changeBgColor 3s infinite;
  -o-animation:       changeBgColor 3s infinite;
  animation:          changeBgColor 3s infinite;
}    

@-webkit-keyframes changeBgColor {
  0% {
    background-color: red;
  }
  25% {
    background-color: green;
  }
  50% {
    background-color: blue;
  }
  75% {
    background-color: black;
  }
  100% {
    background-color: red;
  }
}

@-moz-keyframes changeBgColor {
  0% {
    background-color: red;
  }
  25% {
    background-color: green;
  }
  50% {
    background-color: blue;
  }
  75% {
    background-color: black;
  }
  100% {
    background-color: red;
  }
}

@-o-keyframes changeBgColor {
  0% {
    background-color: red;
  }
  25% {
    background-color: green;
  }
  50% {
    background-color: blue;
  }
  75% {
    background-color: black;
  }
  100% {
    background-color: red;
  }
}

@-ms-keyframes changeBgColor {
  0% {
    background-color: red;
  }
  25% {
    background-color: green;
  }
  50% {
    background-color: blue;
  }
  75% {
    background-color: black;
  }
  100% {
    background-color: red;
  }
}

keyframes changeBgColor {
  0% {
    background-color: red;
  }
  25% {
    background-color: green;
  }
  50% {
    background-color: blue;
  }
  75% {
    background-color: black;
  }
  100% {
    background-color: red;
  }
}

JS Bin Example

答案 1 :(得分:0)

var color = "red"    
setInterval(function() {
    if(color == "red") {
         $('body').stop().animate({backgroundColor: "green"}, 2000);
         color = "green";
    } else if(color == "green") {
         $('body').stop().animate({backgroundColor: "blue"}, 2000);
         color = "blue";
    } else if(color == "blue") {
        $('body').stop().animate({backgroundColor: "red"}, 2000);
        color = "red";
    }
}, 2500);