2013-12-20 181 views
1

我對開發很陌生,所以請原諒我缺乏知識。我正在嘗試更改我正在製作的網頁上的按鈕的背景顏色。我創造了類似的東西。試圖改變按鈕的顏色onclick

在此示例中,我想在日期開啓時將背景顏色更改爲紅色,並在日期關閉時將背景顏色更改爲綠色。

請解釋我做了什麼錯在這裏

<!doctype> 
<html> 
<body> 
<h1>My First Button in Java Script.</h1> 
<p>Please click the button to display the date.</p> 

<!=========this is button=============> 

<button type="button" onclick="myFunction()" id="on" style=background-color:#32CD32>Turn on Date</button> 
<p id="demo"></p> 


<!==== this is the button that will show the date====> 
<script> 
function myFunction(){ 
var x = document.getElementById("demo"); 
var onoff= document.getElementById("on"); 
if (x.innerText=="") 
{ 
    x.innerHTML = Date(); n = "Turn Date Off"; onoff.bgcolor="#FF0000"} 
    else { 
    x.innerHTML =""; n = "Turn Date On"; onoff.bgcolor= "#32CD32"} 

    onoff.innerText = n; } 
</script> 
</body> 
</html> 

提醒您,我複製從W3Schools的這個代碼,然後修改它。

回答

1

要更改元素的背景顏色,您可以使用它。的

onoff.style.background ="#FF0000" 

代替

onoff.bgcolor="#FF0000" 

Js Fiddle

1

你只需要改變語法從改變顏色:

onoff.bgcolor = "#FF0000" 
onoff.bgcolor = "#32CD32" 

到:

onoff.style.backgroundColor = "#FF0000" 
onoff.style.backgroundColor = "#32CD32" 

jsFiddle example

+0

謝謝。那是我正在尋找的令人興奮的! – user3120232