简体   繁体   中英

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. What I've been struggling with is how to integrate transition effect into the setInterval method. I want the new colors to appear with a fade effect, just like the transition property does in CSS. 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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