2017-12-27 6 views
-1

2 초마다 몸의 배경색을 변경하는 웹 페이지를 설정했습니다. 내가 고민하고있는 것은 전환 효과를 setInterval 방법으로 통합하는 방법입니다. 전환 속성이 ​​CSS에서와 마찬가지로 새로운 색상을 페이드 효과와 함께 표시하고 싶습니다. 이러한 변경/전환 배경색에 대해 어떻게 효과를 얻을 수 있습니까?JavaScript에서 setInterval 메서드를 사용하여 TRANSITION 효과를 얻는 방법은 무엇입니까?

여기에 내 코드 : 당신이 전환 할 그것이 얼마나 오래 걸릴 것의 property 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; 
 
}
<html> 
 
<body id="body"> 
 
    <button id="startButton">Start</button> 
 
</body> 
 
</html>

+1

,'그냥'pickRandomColor을()'반환; – gurvinder372

답변

1

. 대신 반환 편곡`의

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>

관련 문제