2012-04-23 62 views
1

我寫了下面的代碼:在懸停上切換課程?

$(document).ready(function() { 
    $("#rade_img_map_1335199662212").hover(function() { 
     $("li#rs1").addClass("active"); //Add the active class to the area is hovered 
    }, function() { 
     $("li#rs1").addClass("not-active"); 
    }); 
}); 

問題是,它似乎沒有切換懸停類?

但是我怎樣才能得到它,以便該類基於懸停和非懸停..切換?

+0

您是否也有html代碼? – 2012-04-23 17:24:31

回答

9

不要懸停出添加不同類只是刪除active

$(document).ready(function(){ 

    $("#rade_img_map_1335199662212").hover(function(){ 

     $("li#rs1").addClass("active"); //Add the active class to the area is hovered 
    }, function() { 
     $("li#rs1").removeClass("active"); 
    }); 

}); 

,或者如果所有元素都是不活動一開始你可能會使用一個函數和toggleClass()方法

$(document).ready(function(){ 

    $("#rade_img_map_1335199662212").hover(function(){ 
     $("li#rs1").toggleClass("active"); //Toggle the active class to the area is hovered 
    }); 

}); 
+0

我有13塊這樣的代碼塊,我應該小型JS嗎? – 2012-04-24 07:57:01

+0

@sp-1986用於生產代碼的縮小通常是一個好主意。但如果你只用一個不同的id/class重複相同的代碼13次,那麼你可以肯定地重新編寫邏輯,以便在縮小代碼之前將代碼縮減爲單個*塊*的代碼。你可以發佈HTML和JS嗎? – 2012-04-24 08:11:56

+0

增加了另一個問題,對不起,如果它的重複..:http://stackoverflow.com/questions/10294156/add-class-and-fadein-using-jquery – 2012-04-24 08:14:21

1

請嘗試如下,

$(document).ready(function() {  
     $("#rade_img_map_1335199662212").hover(function() {  
      $("#rs1") 
      .removeClass("not-active") 
      .addClass("active"); //Add the active class to the area is hovered 
     }, function() { 
      $("#rs1") 
      .removeClass("active"); 
      .addClass("not-active"); 
     });  
    }); 
+0

,如果你知道肯定沒有其他類存在或將稍後再添加,你可以對.attr('class','your-class-here')進行overwtire。只是我5美分。 – GnrlBzik 2012-04-23 17:30:44