2017-12-27 305 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>

相关问题