簡體   English   中英

如何在JavaScript中使用setInterval方法實現過渡效果?

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

我設置了一個網頁,該網頁每2秒更改一次主體的背景顏色。 我一直在努力的是如何將過渡效果集成到setInterval方法中。 我希望新顏色以褪色效果顯示,就像CSS中的transition屬性一樣。 對於這些更改/切換的背景色,我如何實現這種效果?

這是我的代碼:

 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM