简体   繁体   中英

add background color to a div when radio button is checked using css

I have a radio button and I need to add a style to its parent div when the radio button is checked. This I need to do only with css. In the below html, if the radio is checked, i need to apply a color to the div "options"

HTML

<div class="options"> 
<span class="option_radio">
        <input type="radio" name="payMethod" id="payMethod1" value="aaa" >
</span>
<span class="option_image">
    <label for="payMethod1">
        <img src="abc.png" >
    </label>
</span>
</div>

I tried the below approaches but its not coming correctly

.options input[type="radio"]:checked span{
background-color:black;
}

.options input[type="radio"]:checked div.options{
background-color:black;
}

could somebody please help me on this

Sorry, can't do that yet. You can only go down the tree, not up it. You will either need to make the elements you want to style siblings or descendents of the radio button. Ancestor selectors do not yet exist:

http://css-tricks.com/parent-selectors-in-css/

<input type="radio" name="payMethod" id="payMethod1" value="aaa" />

<div class="options"> 
<span class="option_radio">
</span>
<span class="option_image">
    <label for="payMethod1">
        <img src="abc.png" />
    </label>
</span>
</div>

css

input[type='radio']:checked + div.options {
  background-color:green;
}
input[type='radio']:checked + div.options span {
  background-color:red;
}  

That would require using parent selectors from CSS4 http://www.w3.org/TR/selectors4/ Unfortunately CSS4 is not yet available. So for today it is not possible to do that using pure css.

Javascript is your answer. Provided Vanilla and jQuery examples .

var payMethod = document.querySelector('#payMethod1');

payMethod.onchange = function() {
    alert('clicked')
    // Get span and div
    if(this.checked) {
        var elements = document.querySelectorAll('.option_radio, .options');

        // Loop elements & add class
        for(var i = 0; i < elements.length; i++) {
            if (elements[i].classList)
              elements[i].classList.add("checked");
            else
              elements[i].className += ' checked';
        }
    }
};

//jQuery implementation
$('#payMethod1').change(function() {
   if($(this).is(':checked')) {
       $('.option_radio, .options').addClass('checked');
   }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM