如何在JavaScript中使用SetInterval方法实现过渡效果



我已经设置了一个网页,该网页每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>

设置过渡属性指定您要过渡的属性以及需要多长时间。

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>

最新更新