2012-01-04 25 views
0

用下面的函數我在窗口中心的對象,如果用戶選擇這樣:jQuery |中心對象上的窗口大小調整

var showObj = function(obj) { 

    setTimeout(function() { 
     if(opts.centerObj == true) { 
      var cssProps = { 
       'position' :'absolute', 
       'top' : (($(window).height() - $(obj).outerHeight())/2)+'px', 
       'left' : (($(window).width() - $(obj).outerWidth())/2)+'px' 
      } 
      obj.css(cssProps).fadeIn('slow'); 
     } 
      else { 
       obj.fadeIn('slow'); 
      } 
    }, 1500); 

} 

但我要調整此功能,或者使一個又一個,如果窗口,將集中的對象調整大小。

我見過我可以用這個:

$(window).resize(function() { 
    obj.css(cssProps); 
}); 

但我認爲我錯了,因爲當我調整窗口的大小沒有任何反應。

所以,有人可以告訴我如何創建那個我需要的功能或調整當前的功能,所以它呢?

+1

這已被問過一個bajillion倍... [中央關於調整大小過於]的 – Neal 2012-01-04 15:45:03

+0

可能重複(http://stackoverflow.com/questions/5634444/center-on-resize-too) – Neal 2012-01-04 15:47:05

回答

2

這取決於你在呼喚cssProps。由於它在一個私人函數內,除非你聲明它是不可訪問的。我認爲做你想做的最簡單的方法是取出創建JS對象的代碼並將其放入它自己的函數中。

var showObj = function(obj) { 

    setTimeout(function() { 
     if(opts.centerObj == true) { 
      var cssProps = getProps(obj); 
      obj.css(cssProps).fadeIn('slow'); 
     } 
     else { 
      obj.fadeIn('slow'); 
     } 
    }, 1500); 

} 

var getProps = function(obj) { 

    return { 
     'position' :'absolute', 
     'top' : (($(window).height() - $(obj).outerHeight())/2)+'px', 
     'left' : (($(window).width() - $(obj).outerWidth())/2)+'px' 
    } 
} 

$(window).resize(function() { 
    var cssProps = getProps(obj); 
    obj.css(cssProps); 
}); 
2

這個問題被問和之前刪除和here is my solution(僅10K)

jQuery.fn.center = function() { 

    var $self = $(this), _self = this; 
    var window_resize = function(){ 
     var window_obj = $(window); 
     $self.css({ 
      "position": "absolute", 
      "top": ((window_obj.height() - _self.outerHeight())/2), 
      "left": ((window_obj.width() - _self.outerWidth())/2) 
     }); 
    } 
    $self.bind('centerit', window_resize).trigger('centerit'); 
    $(window).bind('resize', function(){ 
     $self.trigger('centerit'); 
    }); 
    return _self; 

} 


$('div').center(); 

小提琴:http://jsfiddle.net/maniator/JeBHJ/

+0

你鏈接返回找不到頁面。 – Seth 2012-01-04 15:50:02

+0

@Seth這是一個10k的被刪除的問題 – Neal 2012-01-04 15:50:31

+0

我知道,但我不是在尋找另一個插件,我有一些其他的插件。我想用一個簡單的函數來做這件事,因爲我會在插件中使用它。 – Roland 2012-01-04 15:54:53