【问题标题】:How to achieve TRANSITION effect with setInterval method in JavaScript?JavaScript 中如何用 setInterval 方法实现 TRANSITION 效果?
【发布时间】: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


【解决方案1】:

设置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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-11
    • 2012-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-18
    • 2016-07-11
    相关资源
    最近更新 更多