如何制作一个JS功能,可以从类似的原点颜色转换为某种颜色?

时间:2015-04-08 09:18:45

标签: javascript

例如。我有一个粉红色,我希望它在3秒内变成红色,时间是我可以改变的参数,原点和目标颜色也是。

从此:How to make background gradually change colors?

function animateBg(i) {
    document.body.style.backgroundColor = 'hsl(' + i + ', 100%, 50%)';

    setTimeout(function() {
        animateBg(++i)
    }, i);
}
animateBg(0);​

我可以改变颜色,但是如何制作相似的颜色以及如何控制时间?

1 个答案:

答案 0 :(得分:1)

这样做:

function changeColor(){
  document.getElementById("theDiv").className = "red";
}
.pink{
  background-color: pink;
}

.red{
  background-color: red;
}

div{
  -webkit-transition: 3s; /* Firefox */
  -moz-transition: 3s; /* WebKit */
  -o-transition: 3s; /* Opera */
  transition: 3s; /* Standard */
  width: 50px;
  height: 50px;
}
<div id="theDiv" class="pink"></div>
<button onclick="changeColor()"> Change Color </button>

请注意,“3s”位于代码段的CSS中。

http://www.w3schools.com/css/css3_transitions.asp