2015-01-08 29 views
-1

我一直在試圖看看是否有可能創建一個循環背景,它按照外觀順序從列表中的一種顏色更改爲下一種顏色。 (顏色是:紅色,橙色,黃色,綠色,藍色和紫色。)我希望它能起作用,並給頁面帶來「彩虹」式的外觀。我認爲將HTML與JavaScript混合會起作用,但它顯然似乎只顯示文本,甚至不顯示第一個背景變化。HTML/Javascript彩虹背景代碼不起作用

的代碼是:

<HTML> 
<HEAD> 
</HEAD> 
<BODY> 

<script> 
function Red() { 
bgcolor Red; 
ColorOrange(); 
} 

function Orange() { 
bgcolor Orange; 
ColorYellow(); 
} 

function Yellow() { 
bgcolor Yellow; 
ColorGreen(); 
} 

function Green() { 
bgcolor Green; 
ColorBlue(); 
} 

function Blue() { 
bgcolor Blue; 
ColorPurple(); 
} 

function Purple() { 
bgcolor Purple; 
ColorRed(); 
} 



function ColorRed() 
{ 
setTimeout("Red", 1000); 
} 

function ColorOrange() 
{ 
setTimeout("Orange", 1000); 
} 

function ColorYellow() 
{ 
setTimeout("Yellow", 1000); 
} 

function ColorGreen() 
{ 
setTimeout("Green", 1000); 
} 

function ColorBlue() 
{ 
setTimeout("Blue", 1000); 
} 

function ColorPurple() 
{ 
setTimeout("Purple", 1000); 
} 
</script> 

There is text here, but it's sorta not related to this so I replaced it with this! 
</BODY> 
</HTML> 
+1

你申報了很多方法,但你不叫任何人。另外,我不認爲'bgcolor Blue'是有效的JavaScript。 – GolezTrol

+1

通過'彩虹',我想到了多種顏色,但是您的代碼和您的解釋表明您希望將完整的背景更改爲每秒變色的一種顏色變化。是對的嗎? – GolezTrol

+0

是的,這是正確的。我試圖實現HTML代碼,將背景顏色bgcolor更改爲我的JavaScript。有沒有辦法將HTML放入我的JavaScript? – TheWaffleDimension

回答

2

我認爲最簡單的解決辦法是把顏色的數組。您可以簡單地遍歷數組,並使用setInterval函數每秒更改顏色。

(function() { // Wrap in a function to not pollute the global scope 
 

 
    // Colors. These are the color names you can use in CSS. You could use color codes 
 
    // like #rrggbb as well. 
 
    var colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']; 
 

 
    var colorIndex = 0; 
 

 
    setInterval(function(){ 
 
    // Set the color and increment the index. 
 
    document.body.style.backgroundColor = colors[colorIndex++]; 
 

 
    // Wrap the index if it goes past the length of the array. % is modulo. 
 
    colorIndex %= colors.length; 
 
    }, 1000); 
 
})();

+0

謝謝!這很奏效。 – TheWaffleDimension

0

沒有必要使用Java。

此的任何標籤:

style="linear-gradient(red,orange,yellow,green,cyan,blue,magenta)" 
+0

JavaSCRIPT。 ____ –