2012-09-10 72 views
-3
<style type="text/css"> 
.radiostyle { 
    background-color: #999; 
} 
</style> 

<label for="a1" class="radiostyle"> 
<Input type = radio Name = 1 Value = 100 Onclick="changecss()" id="a1"> 
100 bucks</label> 

函數changecss()的代碼是什麼,以便當單擊單選按鈕時,單選背景將更改爲其他某種顏色。綠色。請幫助,我在網上查找了幾個小時,但沒有解決方案。如何在點擊時更改單選按鈕

+2

你會很樂意與一個jQuery的解決方案或它必須是純JavaScript? –

+5

您是如何搜尋小時而未找到解決方案的? http://xahlee.info/js/css_change.html(第一谷歌結果)http://stackoverflow.com/questions/195951/change-an-elements-css-class-with-javascript – jeremyharris

+3

問了很多次,很容易搜索。此外,還有一個':checked:'CSS3僞類,它可以在沒有javascript的情況下工作。 –

回答

1
function changecss() { 
    var rb = document.getElementsByClassName('radiostyle'); 
    rb[0].style.backgroundColor = 'red'; 
}​ 

jsFiddle example

0

如果您正在使用jQuery,你可以這樣做:

$("#a1").click(changecss); 

function changecss() 
{ 
$(this).parent().removeClass("radiostyle").addClass("selectedStyle"); 
}​ 

對於直接的JavaScript,其中selectedStyle已定義你的風格:

function changecss() 
{ 
    this.parentNode.setAttribute("class", "selectedStyle"); 
} 
5

你可以使用一個唯一的CSS的解決方案(CSS3):

HTML:

<input type="radio" name="1" value="100" id="a1"> 
<label for="a1" class="radiostyle">100 bucks</label> 

CSS:

.radiostyle { 
    background-color: #999; 
} 
input[type=radio]:checked+label { 
/* Or `#a1:checked+label` if you only want it for that input */ 
    background-color: red; 
} 

http://jsfiddle.net/peSJG/

+0

嗨,請參閱http://jsfiddle.net/JHMqG/該解決方案在貓選項中起作用,但在dog選項中不起作用,這是我真正需要幫助的。 – user1660344

+0

@ user1660344解決方法如下:http:// jsfiddle.net/JHMqG/5/ – Oriol

0

這應該可以幫助你..

  • 你必須使用id屬性
  • 得到使用getElementById()
  • 現在元素來改變你的屬性喜歡

.radiostyle { 背景-color:#999; } .radiostyle1 { background-color:#ffff; }

<script type="text/javascript"> 
    function changecss() 
    { 
     var e= document.getElementById("a1"); 
     e.className="radiostyle1"; 
    } 
</script> 



<label for="a1" id="a1" class="radiostyle"> 
    <Input type ="radio" id="r1" Name ="r1" Value = 100 Onclick="changecss()" id="a1"> 
    100 bucks 
</label>