2013-12-10 181 views
1

我遇到了一個選中的單選按鈕的樣式,我的代碼一般工作,除了有一個DEFAULT選中單選按鈕時,一些麻煩,然後造型不再工作,直到我檢查一個不同的單選按鈕。我的問題是,如何在缺省情況下選中應用於單選按鈕的同樣樣式,並且可以僅使用CSS來完成此操作?選中單選按鈕樣式

這裏是我的代碼:

HTML

<div class="accessOptions"> 
    <div class="option"> 
     <input type='radio' id="1" name='11' checked='checked' class="highlight"/> 
     <label for 1>Open to Anyone</label> 
    </div> 
    <div class="option"> 
     <input type="radio" id="2" name="11" /> 
     <label for 2>Only to Allowed Senders</label> 
    </div> 
</div> 

CSS:

.highlight { 
    background: #5479ab; 
} 

的jQuery:

$(document).ready(function(){ 
    $('input:radio').change(function(){ 
     var $this = $(this); 
      $this.closest('.accessOptions').find('div.highlight').removeClass('highlight'); 
     $this.closest('.option').addClass('highlight'); 
    }); 
}); 

鏈接的jsfiddle: http://jsfiddle.net/priswiz/BMB9R/

+1

邊注:應該是'<標籤= 「1」>'和'不'

回答

3

最簡單的方法是簡單地將類highlight添加到div,其中包含默認選擇的無線電。由於你的JS一旦選擇了另一臺收音機就會刪除這個類,這應該可以工作得很好。這裏是一個小提琴:http://jsfiddle.net/w4UDz/1/

<div class="accessOptions"> 
    <div class="option highlight"> 
     <input type='radio' id="1" name='11' checked='checked'/> 
     <label for="1">Open to Anyone</label> 
    </div> 
    <div class="option"> 
     <input type="radio" id="2" name="11" /> 
     <label for="2">Only to Allowed Senders</label> 
    </div> 
</div> 
1

你需要預先檢查元素

所以加.filter(':checked').change();到您的代碼上運行代碼..

$(document).ready(function(){ 
    $('input:radio').change(function(){ 
     var $this = $(this); 
     $this.closest('.accessOptions').find('div.highlight').removeClass('highlight'); 
     $this.closest('.option').addClass('highlight'); 
    }).filter(':checked').change(); 
}); 

的另一個問題是,在你的HTML您應用類到錯誤的元素..

如果您要模仿您的代碼的作用,您應該將.highlight類添加到div而不是input這樣

<div class="option highlight"> 
    <input type='radio' id="1" name='11' checked='checked' /> 
    <label for 1>Open to Anyone</label> 
</div> 

至少那是你的代碼做什麼..

4

您可以使用CSS3的:checked選擇。

.highlight:checked { 
    background: #5479ab; 
} 

無需腳本。


編輯:

給出的細節,我在我的第一個回答時沒趕上,這裏是你如何應用樣式有問題的radio的父div

$(document).ready(function(){ 

    $('input:radio.highlight:checked').parent(".option").addClass("highlight"); 

    $('input:radio').change(function(){ 
     var $this = $(this); 
      $this.closest('.accessOptions').find('div.highlight').removeClass('highlight'); 
     $this.closest('.option').addClass('highlight'); 
    }); 
}); 
+0

!爲最簡單的解決方案 –

+1

神聖的廢話,我得到感嘆號?這比投票更好。 @php_nub_qq – Kehlan