2010-07-23 62 views
0

基本上我有6个标签充当按钮。当他们被点击时,他们从白色变为蓝色。当您点击另一个标签时,之前的蓝色标签会再次变成白色,并且当前的点击标签会变成蓝色。HTML/CSS/JS想要为一组对象着色,然后为其中一个对象着色?

目前下面的代码将它们全部设置为白色,但是看起来不会将新单击的标签着色为蓝色。但是,如果我注释掉该行:

document.getElementsByTagName('label')。style.backgroundColor ='#fff';

然后每个点击的标签都会变成蓝色,但是当我点击一个新的标签时它仍然是蓝色。所以我需要知道的是如何将标签类背景设置为白色,然后将最近点击的标签的背景变为蓝色。

结果应该是每次只有最近点击的标签背景应该是蓝色而其他的是白色的。

在此先感谢

<script = "text\javascript"> 
     function toggle(label) { 
      document.getElementById('one').style.display = 'block'; 
      document.getElementsByTagName('label').style.backgroundColor = '#fff'; 
      document.getElementById(label).style.color = 'rgb(54, 95, 145)'; 
      document.getElementById(label).style.backgroundColor = 'rgb(193,203,225)'; 
     } 

    </script> 

    <label id='Label6' class='button' onmousedown = 'toggle("Label6")'>Personal Details</label> 
    <label id='Label1' class='button' onmousedown = 'toggle("Label1")'>Education</label> 
    <label id='Label2' class='button' onmousedown = 'toggle("Label2")'>Achievements</label> 
    <label id='Label3' class='button' onmousedown = 'toggle("Label3")'>Work Experience </label> 
    <label id='Label5' class='button' onmousedown = 'toggle("Label5")'>IT Skills</label> 
    <label id='Label4' class='button' onmousedown = 'toggle("Label4")'>Languages</label> 

回答

0

您所标明的行不正确。此调用:

document.getElementsByTagName('label'); 

返回一个元素数组,该数组没有属性style。您需要遍历结果:

var els = document.getElementsByTagName('label'); 
for (var i=0; i<els.length; i++) { 
    els[i].style.backgroundColor = '#fff'; 
} 

或者,使用像Mahesh建议。

0

jQuery的真正的亮点在这里。我会higly建议使用它

你可以做这样的事情

$("label").onclick(function() { 
    $("label[id=^label]").css('backgroundcolor', 'white'); 
    $(this).css('backgroundcolor', 'blue'); 
}); 

PS:我还没有测试的代码