JavaScript-更改输入标签颜色?

时间:2015-08-06 13:49:21

标签: javascript css

我想通过JavaScript更改输入标签的颜色。我对列表项和选择输入做了同样的事情。他们都很好。但是,当我以相同的方式书写时,它不会改变标签的颜色。我的代码不正确吗?还是有其他方式以类似的方式完成这项任务?

我的代码:

    //Highlights current page from submenu- This works
    link = document.getElementById("<?php echo "$link";?>");  
    link.style.background = "#CCCCCC";
    link.style.color = "#3385D6";
    link.style.fontWeight = "bold";     
    link.style.border = "1px solid";
    link.style.borderColor = "#BBBBBB";

    //Highlights current submenu tab
    subbtn = document.getElementById("<?php echo "$subTab";?>");
    subbtn.checked= true;   
    //Doesn't work
    subbtn.style.background = "#CCCCCC";
    subbtn.style.color = "#3385D6";
    subbtn.style.fontWeight = "bold";   

我的HTML:

<input type="radio" id="reveal-email">
<li><label for="reveal-email" >Tab that i want to change</label></li>

1 个答案:

答案 0 :(得分:0)

Based on your using a checked property on it, I'm going to guess that subbtn is an input type="checkbox" or input type="radio". So you're not setting the color and background of the label at all, that's a separate element.

If your HTML has the input inside the label (as is frequently the case), then:

var parentStyle = subbtn.parentNode.style;
parentStyle.background = "#CCCCCC";
parentStyle.color = "#3385D6";
parentStyle.fontWeight = "bold";

Live Example:

var subbtn = document.getElementById("subbtn");
var parentStyle = subbtn.parentNode.style;
parentStyle.background = "#CCCCCC";
parentStyle.color = "#3385D6";
parentStyle.fontWeight = "bold";
<label>
  <input type="checkbox" id="subbtn"> This is the label
</label>

(The HTML you added indicates that you're using for instead, so see below.)

If your HTML has them separated and linked by the for attribute on the label matching the id of the checkbox, then the first line changes somewhat:

var parentStyle = document.querySelector('label[for="' + subbtn.id + '"]').style;

Live Example:

var subbtn = document.getElementById("subbtn");
var parentStyle = document.querySelector('label[for="' + subbtn.id + '"]').style;
parentStyle.background = "#CCCCCC";
parentStyle.color = "#3385D6";
parentStyle.fontWeight = "bold";
<input type="checkbox" id="subbtn">
<label for="subbtn">This is the label</label>

If you're not linking them in either way, you should, so that clicking the label will toggle the checkbox.