2012-10-30 38 views
0

我用下面創建一個撥動開關,而不是單選按鈕 - 它的偉大工程CSS變化積極選擇無線電

.switch 
{ 
    display: block; 
    float: left; 
    -moz-border-radius: 6px; 
    -webkit-border-radius: 6px; 
    border-radius: 6px; 
    font-weight: bold; 
    text-transform: uppercase; 
    background: #eee; 
    border: 1px solid #aaa; 
    padding: 2px; 
    box-shadow: inset 0 2px 5px rgba(0,0,0,0.2); 
    margin-left: 20px; 
} 

.switch input[type=radio] 
{ 
    display: none; 
} 

.switch label 
{ 
    display: block; 
    float: left; 
    padding: 3px 6px; 
    -moz-border-radius: 5px; 
    -webkit-border-radius: 5px; 
    border-radius: 5px; 
    color: #aaa; 
    cursor: pointer; 
} 

.switch label:hover 
{ 
    text-shadow: 0 0 2px #fff; 
    color: #888; 
} 

.switch label.checked 
{ 
    background: #8fc800; 
    color: #eee; 
    text-shadow: 0 -1px 1px rgba(0,0,0,0.5); 
    background: -webkit-linear-gradient(top, #8fc800, #438c00); 
    background: -moz-linear-gradient(top, #8fc800, #438c00); 
    background: -ms-linear-gradient(top, #8fc800, #438c00); 
    cursor: default; 
} 

和HTML:

<div class="switch"> 
    <input type="radio" name="weekly_new" id="weekSW-0" <?=$yes_checked?> value="Yes" /> 
    <label for="weekSW-0" id="yes">ON</label> 
    <input type="radio" name="weekly_new" id="weekSW-1" <?=$no_checked?> value="No" /> 
    <label for="weekSW-1" id="no">OFF</label> 
</div> 

和jQuery:

<script> 
    $(".switch label:not(.checked)").click(function(){ 
     var label = $(this); 
     var input = $('#' + label.attr('for')); 

     if (!input.prop('checked')){ 
      label.closest('.switch').find("label").removeClass('checked');       
      label.addClass('checked'); 
      input.prop('checked', true); 
     } 
    }); 

    $(".switch input[checked=checked]").each(function(){ 
     $("label[for=" + $(this).attr('id') + "]").addClass('checked'); 
    }); 
    </script> 

正如你所看到的label.checked給出的按鈕它是'看' - 我想要做的是有一個不同的顏色,當No選擇而不是 - 紅色否,綠色是,開創性的吧?

無論如何,不​​能爲我的生命弄清楚,如果這是可以做到

我分配的ID給標籤和例如嘗試

.switch label.checked #yes { blah blah } 

但是,這使得風格無用!

因爲我這樣做了代碼,可以這樣做嗎?

如果我創建了一個小提琴更容易... OBV撥弄不得不把valuse選中=檢查,因爲我通常是從MySQL表加載但它不能

http://jsfiddle.net/aS69U/

回答

3

這個CSS應該一起工作您的代碼:

.switch #no.checked { 
    background:red; 
} 

Demo


很酷的定製的方式;-)

+0

非常感謝,我很接近,但這是非常好的! –