2013-09-27 231 views
2

我在網頁上有多個按鈕。但嘗試在每次點擊時更改單個按鈕的按鈕顏色。我的代碼如下。但不工作....任何幫助?按鈕顏色不會改變多個按鈕的切換

<html> 
<head> 
<script type="text/javascript"> 
function toggleColor(id) { 
if(document.getElementById(id).style.background !== 'rgb(255,0,0)') { 
    document.getElementById(id).style.background = '#FF0000'; 

} 
else { 
    document.getElementById(id).style.background = '#00FF00'; 
} 
} 
</script> 
</head> 
<body> 
<button type="button" id="1" style="background-color:#00FF00;" onclick="toggleColor(this.id)">1</button> 
</body> 

+0

你的代碼看起來就像是在學習會話中間:)我說你還沒有準備好測試自己,只要堅持下去。 (不想聽起來像沖洗,但它是一種更好的學習方式) – Nenotlep

+0

因爲這個'background!=='rgb(255,0,0){',你可能會在你的代碼上得到一個sintax錯誤。嘗試將其更改爲'background!=='#ff0000'){' – DontVoteMeDown

+0

對不起,我的錯誤...但即使#ff0000它不工作.... –

回答

2

您的問題矗立在字符串comparsion

if(document.getElementById(id).style.background !== 'rgb(255,0,0)') 

背景的實際值,設置它的顏色後,是rgb(255, 0, 0)

要當心與RGB內部的空間()

+0

問題在於rgb()中的空格。現在我懂了。謝謝 –

+0

我也建議從背景更改爲backgroundColor,因爲背景是與背景相關的屬性的集合。 http://www.w3schools.com/css/css_background.asp –

+0

你確定。謝謝 –

1

您正在語法錯誤在編寫代碼。將此代碼放入 腳本標記中。

<script> 
function toggleColor(id) { 
if(document.getElementById(id).style.background !== 'rgb(255,0,0)') { 
    document.getElementById(id).style.background = '#FF0000'; 

} 
else { 
    document.getElementById(id).style.background = '#00FF00'; 
    } 
} 
</script> 

希望這能解決您的問題。

謝謝。

+0

只需檢查我的代碼上面。 –

+0

我看到後編輯了您的代碼.....對不起,我正在檢查其他解決方案,但您的代碼爲我工作。 –

+0

沒問題。對不起,我的錯誤 –

4

這是工作代碼。你的代碼有錯誤。沒有腳本標記,如果語句無效。 使用此代碼它正在工作之一。

<html> 
<head> 
<script> 
window.toggle = true; 
function toggleColor(id) { 
console.log(document.getElementById(id).style.background); 
console.log(document.getElementById(id).style.background.indexOf('rgb(0, 255, 0)')); 
if(document.getElementById(id).style.background.indexOf('rgb(0, 255, 0)')>0) 
    document.getElementById(id).style.background = '#FF0000'; 
else if(document.getElementById(id).style.background.indexOf('rgb(255, 0, 0)')>0) 
    document.getElementById(id).style.background = '#00FF00'; 
} 
</script> 
</head> 
<body> 
<button type="button" id="1" style="background:#00FF00;" onclick="toggleColor(this.id)">1</button> 
</body> 
0

主要問題只是您需要包含空格的比較。我的例子傳入按鈕,以便您不需要再次通過ID獲取元素。

JSBIN

HTML:

<!DOCTYPE html> 
<html> 
<head> 
<meta charset=utf-8 /> 
<title>JS Bin</title> 
</head> 
<body> 
    <button type="button" id="1" style="background-color:#00FF00;" onclick="toggleColor(this)">1</button> 
</body> 
</html> 

的JavaScript:

function toggleColor(el) { 
if(el.style.background == 'rgb(0, 255, 0)') { 
    el.style.background = '#FF0000'; 
} 
else { 
    el.style.background = '#00FF00'; 
} 
}