2014-12-05 50 views
0

我有下面的一段代碼,它將一些css應用於某些單選按鈕。這工作正常。 但是,我需要一種方法,當我右鍵單擊其中一個按鈕時,它會將背景顏色切換爲紅色。jQuery - 切換css樣式的單選按鈕標籤的背景顏色

<script> 
$('body').on('contextmenu', '.checkItem', function(event) 
    { 
     event.preventDefault(); 
     //Toggle Colour here 
    } 
</script> 

<style> 
.checkItem 
{ 
    display:inline-block; 
    width: 12em;  
    height: 64px; 
    margin:5px; 
    background: #ddd; 
    border-radius: 4px; 
    position: relative; 
    box-shadow: 0px 1px 3px rgba(0,0,0,0.5); 
} 

.CheckItem label 
{ 
    display: block; 
    width: 10em; 
    border-radius: 4px; 
    transition: all .5s ease; 
    cursor: pointer; 
    position: absolute; 
    top: 2px; 
    left: 3px; 
    z-index: 100; 
    background: #FFFFFF; 
    color: #EDEDED; 
    padding:5px; 
    box-shadow:inset 0px 1px 3px rgba(0,0,0,0.5); 
    height: 48px; 
} 

.checkItem input[type=radio]:checked + label 
{ 
    background: #CCFFCC; 
    color: #000000; 
} 
</style> 

<div class="checkItem"> 
    <input class="input_checkItem" type="radio" name="n_radio" value="34" id="0" checked="checked"> 
    <label for="0">button1</label> 
</div> 

<div class="checkItem"> 
    <input class="input_checkItem" type="radio" name="n_radio" value="35" id="1" checked=""> 
    <label for="1">button2</label> 
</div> 

我嘗試添加一個類:

$(this).children("label").addClass('colRed'); 

但這並沒有工作。班上出現了,但顏色沒有改變。

最近我有是:

$(this).children("label").toggle(function() 
     { 
      $(this).children("label").css({'background-color' : '#CC9999'}); 
     }, function() { 
      $(this).children("label").css({'background-color' : ''}); 
     }) 

但這設置「標籤」爲「style="display: block;"」而我本來期望「style="background-color":"#CC9999"

我缺少什麼?

回答

0

jQuery的CSS-functionm工作,像這樣:

$(this).css("color", "red"); 

所以,你想應該是這樣的:

$(this).children("label").css('background-color' , '#CC9999'); 

檢查出頁面瞭解更多信息:http://api.jquery.com/css/

+0

'$(本)。兒童( 「標籤」)的CSS({ '背景色': '#CC9999'});',這也是有效的。當你想同時放置多個參數時使用,比如'$(this).css({'overflow':'hidden','height':'60px'})' – dm4web 2014-12-05 23:56:31

+0

歡呼聲,但是這些仍然有設置標籤顯示的影響:沒有,而不是改變顏色 – IGGt 2014-12-08 13:39:58

+0

我希望「.CheckItem標籤」是一個錯字,請注意Css-Class-Case – 2014-12-09 07:17:40

0

OK ,它不像使用'toggle'那樣乾淨,但它似乎工作:

$('body').on('contextmenu', '.checkItem', function(event) 
    { 
     event.preventDefault(); 

     if($(this).children("label").hasClass('ignore')) 
      { 
       $(this).children("label").removeClass('ignore') 
       $(this).children("label").css('background-color' , ''); 
      } 
     else 
      { 
       $(this).children("label").addClass('ignore') 
       $(this).children("label").css('background-color' , '#CC9999'); 
      } 
    }) 

爲什麼.toggle不起作用我不知道。但目前我有辦法做到這一點。