我如何制作一个JS函数,它可以从相似的原始颜色双向更改为某个颜色

How can I make a JS function that can guadually change to a certain color from a similar origin color?

本文关键字:颜色 原始 相似 何制作 一个 函数 JS      更新时间:2023-09-26

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

由此可知:如何使背景逐渐变色?

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

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

这样做:

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>

请注意,"3"在代码段的CSS中。

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