简体   繁体   English

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

[英]How to achieve TRANSITION effect with setInterval method in JavaScript?

I've set up a web page which changes the background color of the body after every 2 seconds. 我设置了一个网页,该网页每2秒更改一次主体的背景颜色。 What I've been struggling with is how to integrate transition effect into the setInterval method. 我一直在努力的是如何将过渡效果集成到setInterval方法中。 I want the new colors to appear with a fade effect, just like the transition property does in CSS. 我希望新颜色以褪色效果显示,就像CSS中的transition属性一样。 How can I achieve this effect for these changing/switching background colors? 对于这些更改/切换的背景色,我如何实现这种效果?

Here's my code: 这是我的代码:

 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> 

Set the transition property specifying which property you want to transition and how long it will take. 设置过渡属性,以指定要过渡的属性以及所需的时间。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM