2013-09-27 39 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'; 
} 
}