javascript - JavaScript中如何通过setInterval方法实现TRANSITION效果?

标签 javascript html css dom css-transitions

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

相关文章:

javascript - 如何居中对齐图标和文本?

javascript - 检测浏览器大小并为每个分辨率应用 css

javascript - 关闭特定页面上的 CSS 工作表

javascript - 如何在 CSS 中选择 &lt;script&gt; 标签?

html - 如何水平划分网页?

css - 关闭按钮在 CSS 弹出窗口中的位置

javascript - 为什么要使用 "text/javascript"?

javascript - 有没有办法通过代码将一个长字符串压缩成一个较小的字符串,反之亦然?

html - 保存时 CSS 样式表未链接到 HTML

css - 未读数据的 QTabBar 选择器