2011-05-02 75 views
1

我有固定的位置格與固定的高度/寬度。調整大小和居中固定位置格與jquery

該div使用的位置是

position:fixed;

left = 50%; margin-left = - (width/2) top = 50%; margin-top:= - (width/2)

div有黑色背景。

我想要做的是,當一個按鈕被按下計算的新內容的大小(隱藏DOM元素)

褪色內容的DIV出,動畫它調整到新的內容大小(保持居中)。

淡出的新內容英寸

有什麼用jQuery做到這一點最簡單的方法?

+0

,我給多了一個解決方案...嘗試它會成功。 – kobe 2011-05-02 03:52:59

回答

0

你可以這樣做一個也

this=$('#yourDiv'); 

    this.css("position","absolute"); 
     this.css("top", ($(window).height() - this.height())/2+$(window).scrollTop() + "px"); 
     this.css("left", ($(window).width() - this.width())/2+$(window).scrollLeft() + "px"); 

這是我的應用程序之一,嘗試,如果你需要任何定製應該居中

重構。

function centerPopup() { 

    var windowWidth = document.body.clientWidth; 
    var windowHeight = document.body.clientHeight; 
    var popupHeight = $('#popupplaceholder').height(); 
    var popupWidth = $('#popupplaceholder').width(); 
     if (popupWidth > windowWidth) { 
     popupWidth = (windowWidth) * (0.9); 
    } 
    if (popupHeight > windowHeight) { 
     popupHeight = (windowHeight) * (0.9); 
    } 
    //centering 
    var objControl = document.getElementById("yourDIV"); 
    if (objControl != null) { 
     if (objControl.offsetParent != null) { 
      var left = (objControl.offsetParent.clientWidth/2) - (objControl.clientWidth/2) + objControl.offsetParent.scrollLeft; 
      var top = (objControl.offsetParent.clientHeight/2) - (objControl.clientHeight/2) + objControl.offsetParent.scrollTop; 
      $('#yourDIV').css({ 
       "position": "absolute", 
       "top": top, 
       "left": left 
      }); 
     } 
    } 
} 
0

試試這個:http://jsfiddle.net/EpzDM/

它的工作原理,但我不懷疑的JavaScript可能會得到改善。

的JavaScript:

var $box = $('#box'); 
var $boxInner = $box.find(' > div'); 

var fixIt = function() { 
    var newWidth = 300; 
    var newHeight = 150; 

    $boxInner.fadeOut(function() { 
     $box.animate({ 
      marginLeft: -newWidth/2, 
      marginTop: -newHeight/2, 
      width: newWidth, 
      height: newHeight 
     }, 500, function() { 
      $boxInner.fadeIn(); 
     }); 
    }); 
}; 

$(window).resize(function() { 
    $box.css({ 
     marginLeft: -$box.width()/2, 
     marginTop: -$box.height()/2 
    }); 
}).resize(); 

$('<button>Clicky!</button>').appendTo(document.body).click(fixIt).css({ 
    position: 'fixed', 
    top: 0, 
    left: 0 
}); 

CSS:

#box { 
    width: 200px; 
    height: 100px; 
    background: #ccc; 
    position: fixed; 
    left: 50%; 
    top: 50% 
} 

HTML:

<div id="box"> 
    <div> 
     <p>Contents of div</p> 
     <p>Contents of div</p> 
     <p>Contents of div</p> 
    </div> 
</div>