2012-03-09 4 views
1

jquery를 사용하여 페이지의 사용자 위치에 따라 클래스를 변경하는 div가 있습니다. 이 함수는 다음과 같습니다.jquery가있는 div의 클래스 변경

$(function(){ 

    var menu = $('#menu'), 
     pos = menu.offset(); 

     $(window).scroll(function(){ 
      if($(this).scrollTop() > pos.top+menu.height() && menu.hasClass('default')){ 
       menu.fadeOut('slow', function(){ 
        $(this).removeClass('default').addClass('fixed').fadeIn('slow'); 
       }); 
      } else if($(this).scrollTop() <= pos.top && menu.hasClass('fixed')){ 
       menu.fadeOut('slow', function(){ 
        $(this).removeClass('fixed').addClass('default').fadeIn('slow'); 
       }); 
      } 
     }); 

}); 

그러나 특수 클래스/이름으로 링크/버튼을 클릭하면 div 클래스도 변경하고 싶습니다.

나는 나쁜 시도를했다. 그러나 나는 이것을 이전 기능에 어떻게 통합 할 수 있을까? 와에 .. "만약 다른"

$(".closemeny").click(function() { 
    menu.fadeOut('slow', function(){ 
     $('#menu').removeClass('fixed').addClass('default').fadeIn('slow'); 
}); 

답변

3

나는 완전히 이해하지 않습니다하지만 난 균열 할게요 :

그냥 별도로 .click 기능을 유지하거나로 이동 귀하의 경우/다른 {} '에스.

$(function(){  
    var menu = $('#menu'), 
     pos = menu.offset(); 

    $(window).scroll(function(){ 
     if($(this).scrollTop() > pos.top+menu.height() && menu.hasClass('default')){ 
      menu.fadeOut('slow', function(){ 
       $(this).removeClass('default').addClass('fixed').fadeIn('slow'); 
      }); 

      //you can paste it here 

     } else if($(this).scrollTop() <= pos.top && menu.hasClass('fixed')){ 
      menu.fadeOut('slow', function(){ 
       $(this).removeClass('fixed').addClass('default').fadeIn('slow'); 
      }); 

      //or you can paste it here 
     } 
    }); 

    //or you can leave it here to apply to all cases 
    $(".closemeny").click(function() { 
     menu.fadeOut('slow', function(){ 
      $('#menu').removeClass('fixed').addClass('default').fadeIn('slow'); 
     }); 
    }); 
}); 
+0

정말 잘됩니다! 그러나 다시 스크롤 할 때 레이어가 돌아옵니다. 누군가가 "클로즈 메니 (closemeny)"를 클릭 한 후 레이어를 비활성화하는 방법이 있습니까? 페이지를 새로 고침 할 때까지 돌아 오지 않습니다. – user681061

+0

div를 제거하기 위해 방금 추가했습니다. menu.fadeOut ('slow', function() { $ ('# menu'). remove(); – user681061

1

당신이 할 수있는 일은 그냥 지나치지 않게 보관할 수있는 편리한 기능을 만드는 것입니다. 나는 그 사건들을 결합하는 데 도움이 될 것이라고 생각하지 않는다. 그들이 똑같은 일을하더라도 그들은 다릅니다.

var changeClass = function (c1, c2) { 
    menu.fadeOut('slow', function() { 
     $(this).removeClass(c1).addClass(c2).fadeIn('slow'); 
    }); 
}; 

$(window).scroll(function() { 
    if ($(this).scrollTop() > pos.top + menu.height()) { 
     changeClass('default', 'fixed'); 
    } else if ($(this).scrollTop() <= pos.top) { 
     changeClass('fixed', 'default'); 
    } 
}); 

$(".closemeny").click(function() { 
    changeClass('fixed', 'default'); 
}); 
+0

정확한 해결책을 제안하려고했습니다. . 잘 했어. – Jlange

관련 문제