2014-12-29 18 views
1

필자를 위해 센터링 할 플러그인을 만들고 싶습니다만, 윈도우 크기 조정 후 모든 인스턴스를 재실행하기를 자동화하고 싶습니다. 여기에 몇 가지 (크기 조정을하지 않는) 코드가 있습니다 : 내가하고 싶은 것이윈도우에서 jquery 플러그인 인스턴스를 다시 실행하십시오.

$.fn.centerize = function(){ 
    var divWidth = this.width(), 
     screenWidth = $(window).width(), 
     margin = (screenWidth - divWidth)/2; 

    this.css({'margin-left':margin + 'px', 'margin-right': margin + 'px'}); 
    $(window).resize(function(){ 
     this.centerize(); 
    }); 
} 

모두는, 예를 들어, 일부 DIV 요소에 한 번만이 플러그인을 실행하는 것입니다 :

$('.myCenteredDiv').centerize(); 

을 그리고 브라우저 창 크기를 조정하면, 여백 설정을 다시 계산해야 새 것. 다음과 같은 추가 코드를 추가하고 싶지 않습니다.

$(window).resize(function(){ 
    $('.myCenteredDiv1').centerize(); 
    $('.myCenteredDiv2').centerize(); 
    $('.myCenteredDiv3').centerize(); 
}); 

가능합니까? 모든 제안을 주시면 감사하겠습니다. 컨텍스트

답변

1

문제 :

$(window).resize(function(){ 
    this.centerize(); 
}); 

시도는 '이'또 다른 임시 변수 할당 :

$.fn.centerize = function(){ 
    var divWidth = this.width(), 
     screenWidth = $(window).width(), 
     margin = (screenWidth - divWidth)/2, 
     _this = this; 

    this.css({'margin-left':margin + 'px', 'margin-right': margin + 'px'}); 
    $(window).resize(function(){ 
     _this.centerize(); 
    }); 
} 

을 또는 다른 범위에 컨텍스트를 바인딩 $ .proxy를 사용하려고 할 수 있습니다

$.fn.centerize = function(){ 
    var divWidth = this.width(), 
     screenWidth = $(window).width(), 
     margin = (screenWidth - divWidth)/2; 

    this.css({'margin-left':margin + 'px', 'margin-right': margin + 'px'}); 
    $(window).resize($.proxy($.fn.centerize, this); 
} 
+0

sooo 간단 : 문제가 해결되었습니다. 감사합니다. – mrmnmly