2014-04-05 4 views
0

JavaScript가 새로 도입되었으며 약간의 도움이 필요합니다. 내 웹 페이지의 배경색이 모두 #003372에서 #FFFFFF까지 변경된 다음 해당 순서 (1000 밀리 초)로 모두 #BE2E37에서 임의로 모두 생성하지 않도록하고 싶습니다. 이유는 왜 내가 내 웹 사이트에서 플래시 동영상을 만들었는지 그리고 나타나는 색상과 일치시키기를 원하기 때문입니다.배경색을 특정 순서대로 변경하십시오.

자바 스크립트 :

<script type="text/javascript"> 
     function changebackground() { 
      var colors = ["#003372","#FFFFFF","#BE2E37"]; 

     setInterval(function() { 
      var bodybgarrayno = Math.floor(Math.random() * colors.length); 
      var selectedcolor = colors[bodybgarrayno]; 
      document.body.style.background = selectedcolor; 
     }, 2000); 
    } 
    </script> 

HTML :

<body onload = changebackground();> 

답변

1

이 시도 : 배열 길이의 끝에 도달 할 때

function changebackground() { 
    var colors = ["#003372","#FFFFFF","#BE2E37"], iColor = 0; 

    setInterval(function() { 
     if (iColor > (colors.length - 1)) iColor = 0; 

     var selectedcolor = colors[iColor]; 
     document.body.style.background = selectedcolor; 
     console.log(iColor); 
     iColor += 1; 

    }, 1000); 
} 

당신은 선언하고 각 간격에 iColor의 값을 증가 할 필요가 0으로 다시 설정

Demo

1

이 CSS 달성 할 수 당신이이 어려운하려는 경우는, 원활한 전환을 할 것입니다

@keyframe changeBackground { 

0%{background-color:#003372;} 

50%{background-color:#FFFFFF;} 

100%{background-color:#BE2E37;} 

} 

#yourbackgrounddiv { 
animation: changeBackground 1s infinte linear; 

} 

애니메이션 태그에 "단계"옵션을 추가 할 수 있습니다. 또한 공급 업체 특정 접두사가 필요합니다. 자세한 내용은 ... http://css-tricks.com/almanac/properties/a/animation/

1
function changebackground() { 
    var colors = ["#003372","#FFFFFF","#BE2E37"]; 
    // declare index variable outside of interval enclosure, 
    // so it's value persists between calls 
    var index = 0; 

    setInterval(function() { 
     // magic maths to determine the current index to use... 
     // will be last index plus one, until on last in array 
     // when it will be zero again... 
     index = (index+1)%colors.length; 
     var selectedcolor = colors[index]; 
     document.body.style.background = selectedcolor; 
    }, 1000); 
} 
관련 문제