最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - toggle class on hover? - Stack Overflow

programmeradmin2浏览0评论

I have written the following code:

$(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");
    });
});

The problem is it doesnt seem to toggle the class on hover?

But how can i get it so that the class toggles based on hover and non-hover..?

I have written the following code:

$(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");
    });
});

The problem is it doesnt seem to toggle the class on hover?

But how can i get it so that the class toggles based on hover and non-hover..?

Share Improve this question edited Apr 23, 2012 at 17:26 j08691 208k32 gold badges268 silver badges280 bronze badges asked Apr 23, 2012 at 17:22 SOLDIER-OF-FORTUNESOLDIER-OF-FORTUNE 1,6545 gold badges39 silver badges68 bronze badges 1
  • Do you have the html code as well? – Jonathan Payne Commented Apr 23, 2012 at 17:24
Add a comment  | 

2 Answers 2

Reset to default 15

Do not add a different class on hover-out just remove the active class

$(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");
  });

});

or if all elements are inactive at first you could use a single function and the toggleClass() method

$(document).ready(function(){

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

});

Try like below,

  $(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)

  1. 暂无评论