2011-08-23 37 views
5

我想動畫一個div來填充屏幕,然後再次返回到原​​始大小。但是,當我讓div填充屏幕時,它不會從中心生成動畫,它從右上角開始。此外,當我最小化它時,它不會回到起始位置,而是回到左上角。我的jsfiddle code here。我試圖讓它從中心的起點平滑地進行動畫製作,填滿屏幕然後像開始時一樣向後移動到起始位置。jQuery:如何使一個居中的div動畫來填充屏幕,同時它仍然居中?

+0

動畫之前你的div已經在左上角,你爲什麼要改變它的樣式? – MatTheCat

回答

3

未經pinouchon使用額外的div的另一種方法。 jsFiddle is here

<html> 
    <head> 
     <script type="text/javascript"> 
      var isFullscreen = false; 

      function fullscreen(){  
       var d = {}; 
       var speed = 900; 
       if(!isFullscreen){ // MAXIMIZATION 
        d.width = "100%"; 
        d.height = "100%"; 
        isFullscreen = true; 
        $("h1").slideUp(speed); 
       } 
       else{ // MINIMIZATION    
        d.width = "300px"; 
        d.height = "100px";    
        isFullscreen = false; 
        $("h1").slideDown(speed); 
       } 
       $("#controls").animate(d,speed);    
      } 

     </script> 
     <style> 
      #controls{ 
       width:300px; 
       height:100px; 
       margin: auto auto auto auto; 
      } 
      body, html{ 
       height:100%; 
      } 

     </style> 

    </head> 
    <body> 
     <h1 align=center> Header (To be covered on Fullscreen) </h1> 
     <div id='controls' style="background-color:green;" align="center"> 
      <input type='button' value='fullscreen' onclick='fullscreen();' /> 
     </div> 
    </body> 
</html> 
4

我建議你移動DIV始終position: relative;,並與position: absolute;包含在一個div,他爲中心this way

這裏是你想要什麼工作的例子:http://jsfiddle.net/FP2DZ/

+0

專業答案!歡呼隊友:-) – deztructicus

+0

@deztructicus不客氣 –

1

我想這是你想要什麼:

<html> 
    <head> 
     <script type="text/javascript"> 
      var isFullscreen = false; 

      function fullscreen(){ 

       var d = {}; 
       var speed = 900; 
       if(!isFullscreen){ // MAXIMIZATION 

        d.width = "100%"; 
        d.height="100%";      
        d.left="0%"; 
        d.top="0%"; 
        d.marginLeft="0px"; 

        $("#controls").animate(d,speed); 
        isFullscreen = true; 

       }else{ // MINIMIZATION 

        d.width="300px"; 
        d.height="100px"; 
        d.left="50%"; 
        d.top="50%"; 
        d.marginLeft="-150px"; 


        $("#controls").animate(d,speed); 
        isFullscreen = false; 
       } 

      } 

     </script> 
     <style> 
      #controls{ 
       width:300px; 
       height:100px; 
       position: absolute; 
       top: 50%; 
       left: 50%; 
       margin-left: -150px; 
      } 
     </style> 
    </head> 
    <body> 
     <h1 align=center> Header (To be covered on Fullscreen) </h1> 
     <div id='controls' style="background-color:green;" align="center"> 
      <input type='button' value='fullscreen' onclick='fullscreen();' /> 
     </div> 
    </body> 
</html> 

但我想我是有點晚了;)