只需修改css以包含
transition
属性,例如:
.organic-body {
height: 100vh;
transition: background-color 1000ms;
}
这意味着任何时候
background-color
性能变化,应逐渐过渡到1000ms以上
编辑
如果您真的必须使用js(我强烈建议您不要使用js),这大概是您需要做的
let frames = 60; // The number of frames. The lower the number, the choppier the transition
let duration = 1000; // How long the transition should take
let from = [255, 0, 0]; // RGB values
let to = [0, 0, 255]; // RGB values
// Calculate the differences between the two
let diff = to.map((v, idx) => v - from[idx]);
// Divide that by the number of frames to find out what change should be made in each frame
let frameChange = diff.map(v => v / frames);
let elem = document.getElementById('example');
let step = 1;
function tick() {
from = from.map((v, idx) => v + frameChange[idx]);
elem.style.backgroundColor = `rgb(${from[0]}, ${from[1]}, ${from[2]})`;
step++;
if (step <= frames) {
setTimeout(tick, duration / frames)
}
}
tick()
div#example {
width: 100px;
height: 100px;
background-color: red;
}
<div id="example">
</div>