【发布时间】:2017-12-27 21:44:05
【问题描述】:
我设置了一个网页,它每 2 秒更改一次正文的背景颜色。我一直在苦苦挣扎的是如何将 transition 效果集成到setInterval 方法中。我希望新颜色以淡入淡出效果出现,就像 CSS 中的过渡属性一样。 我怎样才能为这些不断变化/切换的背景颜色实现这种效果?
这是我的代码:
var startButton = document.getElementById("startButton");
var body = document.getElementById("body");
// Click Event Listener
startButton.addEventListener("click", function() {
setInterval(function() {
body.style.backgroundColor = generateRandomColors();
}, 2000);
});
// GENERATE Random Colors
function generateRandomColors() {
var arr = [];
arr.push(pickRandomColor());
return arr;
}
// PICK Random Color
function pickRandomColor() {
// Red
var r = Math.floor(Math.random() * 256);
// Green
var g = Math.floor(Math.random() * 256);
// Blue
var b = Math.floor(Math.random() * 256);
// RGB
var rgb = "rgb(" + r + ", " + g + ", " + b + ")";
return rgb;
}
<html>
<body id="body">
<button id="startButton">Start</button>
</body>
</html>
【问题讨论】:
-
而不是
return arr;只是return pickRandomColor();
标签: javascript html css dom css-transitions