2017-12-27 306 views
-1

我已經設置了一個網頁,每2秒更換一次身體的背景顏色。我一直在努力的是如何將轉換效果納入setInterval方法。我希望新顏色具有淡入淡出效果,就像CSS中的transition屬性一樣。 如何才能達到這種改變/切換背景顏色的效果?如何在JavaScript中使用setInterval方法實現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>

+1

而是回報改編的',''剛剛返回pickRandomColor()'; – gurvinder372

回答

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>

相關問題