选中复选框后切换背景图像

时间:2013-11-19 17:21:42

标签: javascript jquery html css checkbox

选中复选框时,我需要切换列表项的背景图像。

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");  
}); 

这不起作用,我不确定它是否有语法错误。

我在这里创建了一个jsFiddle:http://jsfiddle.net/kikix2125/McLeC/

2 个答案:

答案 0 :(得分:2)

css方式和切换类怎么样:

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

答案 1 :(得分:0)

除非您在9之前定位IE版本,否则您不需要任何JavaScript来执行此操作;只需使用: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