简体   繁体   中英

Toggle background image when checkbox checked

I need the background image of list items toggled when check box is checked.

HTML:

<input type="checkbox" class="checkbox" value="yes" id="answer" name="answer" data-label="I am over the age of 18" />
<div class="categories row-fluid">
    <div class="span4">
        <ul>
            <li>Full Name</li>
            <li>Current Address</li>
            <li>Address History</li>
        </ul>
    </div>
    <!-- /.span12 -->
</div>

CSS:

.categories ul li {
    background:url(http://s21.postimg.org/j4dl4r30z/pretty_Checkbox.png) no-repeat;
    background-position: 0px 0px;
    padding-left:30px;
    list-style:none;
}

JS:

$('input:checkbox').click(function(){
    $('.categories ul li').css("background-position", "0px -32px");  
}); 

This is not working, I'm not sure if it has syntax errors.

I created a jsFiddle here: http://jsfiddle.net/kikix2125/McLeC/

How about a css way and a toggle class:

CSS:

.categories ul li {
    background:url(http://s21.postimg.org/j4dl4r30z/pretty_Checkbox.png) no-repeat;
    background-position: 0px 0px;
    padding-left:30px;
    list-style:none;
}
.categories ul li.active{
   background-position: 0px -32px;
}

JS:

  $('.checkbox').click(function(){
     $('.categories ul li').toggleClass("active");  
  }); 

Demo

Unless you're targeting versions of IE before 9 you don't need any JavaScript to do this; just use the :checked pseudo-class :

.categories li {
  background: url(http://s21.postimg.org/j4dl4r30z/pretty_Checkbox.png) no-repeat;
  background-position: 0px 0px;
  padding-left: 30px;
  list-style: none;
}

#answer:checked + .categories li {
  background-position: 0px -32px;
}

Take a look at the fiddle .

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