【问题标题】:HTML/CSS/JS Want to colour group of objects and then re-colour one of them?HTML/CSS/JS 想要为一组对象着色,然后为其中一个对象重新着色?
【发布时间】:2010-07-23 15:37:34
【问题描述】:

基本上我有 6 个标签作为按钮。单击它们时,它们会从白色变为蓝色。当您点击另一个标签时,之前的蓝色标签会再次变为白色,当前点击的标签会变为蓝色。

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

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>

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    您突出显示的行不正确。这个电话:

    document.getElementsByTagName('label');
    

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

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

    或者,像 Mahesh 建议的那样使用 jQuery

    【讨论】:

      【解决方案2】:

      Jquery 真的在这里大放异彩。我强烈推荐使用它

      你可以这样做

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

      PS:我没有测试过代码

      【讨论】:

        猜你喜欢
        • 2023-04-07
        • 1970-01-01
        • 2011-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-21
        • 1970-01-01
        相关资源
        最近更新 更多