开发者

HTML/CSS/JS Want to colour group of objects and then re-colour one of them?

Basically i have 6 labels acting as buttons. When they are clicked on, they change from white to blue. As you click on another label, the previously blue label turns to white again and the currently click label turns to blue.

At the moment the code below sets them all to white but then doesnt appear to colour the newly clicked label to blue. However if i comment out the line:

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

Then each label clicked on turns to blue, but it remains blue when i click on a new label. So what i need to know is how to set the label class background to white, but then to turn the background of the recently clicked 开发者_如何转开发label to blue.

The result should be each time only the most recently clicked label background should be blue and the others white.

Thanks in advance

<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>


The line you've highlighted is incorrect. This call:

document.getElementsByTagName('label');

Returns an array of elements, the array doesn't have the property style. You need to loop through the results:

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

Alternatively, use jQuery like Mahesh suggests.


Jquery really shines here. I would higly recommend using it

You can do something like

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

PS: I haven't tested the code

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜