我设置了一个网页,每 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>
最佳答案
设置transition property指定要转换的属性以及需要多长时间。
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;
}
body { transition: background-color 2s; }
<html>
<body id="body">
<button id="startButton">Start</button>
</body>
</html>
关于javascript - JavaScript中如何通过setInterval方法实现TRANSITION效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47993069/