[英]Changing CSS class in jQuery
我正在嘗試更改幾個DIV的CSS類,下面的鏈接是我的jFiddle
唯一的變化是-selected類實際上具有背景圖像,該圖像似乎具有-non-selected類的背景顏色。
另一個問題是在選擇了另一個div之后,您將無法再次選擇第一個div。 jQuery對這些類到底做了什么? 當我將-non-selected類添加到它時,它應該又可以選擇了,對嗎?
jQuery的
$(".selector-box").click(function () {
$(".selector-box-selected").removeClass("selector-box-selected").addClass("selector-box");
$(this).removeClass("selector-box").addClass("selector-box-selected");
});
HTML
<div class="selector-box-selected"></div>
<div class="selector-box"></div>
<div class="selector-box"></div>
<div class="selector-box"></div>
CSS
.selector-box{
margin-bottom:2px;
width:328px;
height:46px;
background-color:rgba(255,255,255,.25);
}
.selector-box-selected{
margin-bottom:2px;
width:351px;
height:46px;
background-image:url(../images/layout/SelectedArrow.png);
}
您應該嘗試添加和刪除類的另一種方法,請嘗試以下一種方法:
$(".selector-box").click(function () {
$('.selector-box').removeClass("selected");
$(this).addClass("selected");
});
我會稍微更改您的代碼
<div name="ss" class="selector-box-selected"></div>
<div name="ss" class="selector-box"></div>
<div name="ss" class="selector-box"></div>
<div name="ss" class="selector-box"></div>
$("div[name=ss]").click(function () {
$("div[name=ss]").removeClass("selector-box-selected").addClass("selector-box");
$(this).removeClass("selector-box").addClass("selector-box-selected");
});
不要介意SS,將其更改為您想要的:D
無法再次選擇第一個事件的問題是click事件未鏈接到該事件,因為您僅將其應用於.selector-box
類的<div>
元素。 除此之外,CSS似乎還不錯,請檢查提琴: http : //jsfiddle.net/9FZcz/2/
已經發布了答案,提出了需要一些重構的解決方案,例如將selected
類添加到選定的元素中,而不是使用單獨的selector-box-selected
和selector-box
類。
雖然我認為您應該執行重構,因為它可以使整體設計更好,並減少CSS代碼重復,但這是一種無需重構代碼的解決方案。
我一直跟蹤最后一個選定的元素,以避免循環遍歷所有框以刪除選定的類。
var selectedBox = $('.selector-box-selected').get();
$('.selector-box').add(selectedBox).click(function () {
if (selectedBox === this) return;
selectedBox = $([this, selectedBox])
.toggleClass('selector-box-selected')
.toggleClass('selector-box')
.get(0);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.