2014-11-04 46 views
0

我周圍點擊時改變元素的研究背景顏色一個簡單的jQuery腳本工作一個要素的變化CSS。jQuery的 - 許多與同級別的識別

這裏是我的代碼:

<script src="//code.jquery.com/jquery-1.10.2.js"></script> 

<div class="radio">Text1</div> 
<div class="radio">Text2</div> 
<div class="radio">Text3</div> 
<div class="radio">Text4</div> 

我想下面的情況發生:

我點擊「文本1」和這個div正在改變他的背景顏色爲紅色,並保持紅色。

我點擊「文本2」和「文本1」的背景顏色會白回來,然後選擇「文本2」的背景顏色是怎麼回事,並保持紅色。

我希望我給你一個很好的說明。

你能不能幫我做嗎?

在此先感謝!

回答

1

$('.radio').click(function(){ 
 
    $('.red').removeClass('red'); 
 
    $(this).addClass('red'); 
 
});
.red{ 
 
background-color: red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
 
<div class="radio">Text1</div> 
 
<div class="radio">Text2</div> 
 
<div class="radio">Text3</div> 
 
<div class="radio">Text4</div>

0

這是一種用純CSS來做到這一點:

input { 
 
    display: none; 
 
} 
 
label { 
 
    display: block; 
 
} 
 
input:checked + label { 
 
    background-color: red; 
 
}
<input id="text1" type="radio" name="g1"> 
 
<label for="text1">Text1</label> 
 
<input id="text2" type="radio" name="g1"> 
 
<label for="text2">Text2</label> 
 
<input id="text3" type="radio" name="g1"> 
 
<label for="text3">Text3</label> 
 
<input id="text4" type="radio" name="g1"> 
 
<label for="text4">Text4</label>