2012-11-21 121 views
1

可能重複:
change background color of li using jquery背景顏色

我試圖改變李的背景顏色ONSELECT '複選框'。

<ul> 
<li><input type="checkbox" /> Link 1</li> 
<li><input type="checkbox" /> Link 2</li> 
<li><input type="checkbox" /> Link 3</li> 
<li><input type="checkbox" /> Link 4</li> 
</ul> 

我需要改變整個線條的背景顏色,當一些選擇複選框。

enter image description here

+0

造型入住或單選按鈕總是痛苦的一**;)我用CSS3希望這將是更好的 – 23tux

回答

2

HTML

<ul> 
<li><input type="checkbox" /> <label> Link 1</label></li> 
<li><input type="checkbox" /> <label> Link 2</label></li> 
<li><input type="checkbox" /> <label> Link 3</label></li> 
<li><input type="checkbox" /> <label> Link 4</label></li> 
</ul>​ 

CSS

label{width:150px; display:inline-block} 
input[type="checkbox"]:checked+label{background:blue; color:white}​ 

DEMO

對於IE,你可以使用圖書館像http://selectivizr.com/

+0

+1對CSS的唯一解決方案。但是,這會在舊版瀏覽器上運行嗎? – Abhilash

+0

不幸的是不適合IE瀏覽器。 :) – Sowmya

1

嘗試了這一點,我認爲它會工作。

$('input[type=checkbox]').click(function(){ 
$('input[type=checkbox]').parent().css('background',''); //This turns all checkboxes background to default 
$(this).parent().css('background','red'); 
}); 
1

試試這個:

$('input[type=checkbox]').click(function(){ 
    if(this.checked) { 
     $(this).parent().css('background','red'); 
    } else { 
     $(this).parent().css('background',''); 
    } 
}); 
0

jQuery的

$('input[type=checkbox]').click(function(){ 
    $(this).parent().toggleClass('highlight'); 
}); 

CSS

.highlight{ 
    background-color:blue; 
} 

我想你想的亮點消失時,該複選框被重新被點擊。這裏的工作jsbin

0
$('li :checkbox').click(function(){ 
    $(this).parent().css('background',$(this):is(":checked")?'blue':''); 
}); 
0

試試這個:

<ul id="myList"> 
     <li><input type="checkbox" /> Link 1</li> 
     <li><input type="checkbox" /> Link 2</li> 
     <li><input type="checkbox" /> Link 3</li> 
     <li><input type="checkbox" /> Link 4</li> 
    </ul> 

    <script type="text/javascript"> 
     $(document).ready(function(){ 
      $('#myList input').each(function(){ 
      console.log(this); 
       $(this).click(function(){ 
       console.log(this); 
        if($(this).prop('checked')){ 
         $(this).parent().css('background','#eee'); 
        } 
        else{ 
         $(this).parent().css('background',''); 
        } 
       }); 
      });    
     }); 

    </script> 
1

試試這個:

http://jsfiddle.net/AHrrP/

HTML

<ul> 
<li><input type="checkbox" /> Link 1</li> 
<li><input type="checkbox" /> Link 2</li> 
<li><input type="checkbox" /> Link 3</li> 
<li><input type="checkbox" /> Link 4</li> 
</ul>​ 

JS

$(function(){ 
    $('input[type="checkbox"]').click(function(){ 
     if(this.checked) 
      $(this).closest('li').addClass('blue'); 
     else 
      $(this).closest('li').removeClass('blue'); 
    }); 
});​ 

CSS

li { 
    padding:4px; 
} 

li.blue { 
    background-color: #08C; 
}​ 
+0

感謝您的幫助Pulkit ..它爲我工作..感謝您的時間.. :) – Gaurav