2012-02-15 56 views
1

您好我我只是最近纔開始學習jQuery和而搞亂以防萬一,我開始從球泡一個scratch.This效果燈箱是我的代碼:jQuery的動畫寬度增加從中間

$(document).ready(function(){ 
      $('a').click(function(){ 


       $('<div id="overlay"></div>').css({opacity:'0' }) 
         .animate({ opacity:'0.7' 
         },1500) 
         .appendTo('body'); 
       $('<div id="container"></div>').css({ 
                backgroundColor:'white', 
                opacity:'0' 

               }) 
               .animate({ 
                 left:'470px', 
                 top:'150px' 
               },'fast') 
               .animate({ 
                 opacity:'1' 
               }) 
               .animate({ 
                 height:'+=255px' 
                 },1000,'swing') 
               .animate({ 
                 width:'+=350px' 
                 },1000,'swing') 
               .animate({ 
                 height:'+=50px' 
                 },1000,'swing') 

               .appendTo('body'); 
       $('<img/>').attr('src',$(this).attr('href')).appendTo('div#container'); 

       return false; 
      }); 


     }) 

雖然試圖設置DIV的中心,我創建2個變量:

var left = ($(window).width() - $('div#container').width())/2 
var top = ($(window).height() - $('div#container').height())/2 

這些形式給出的問題是div的初始寬度和高度設置爲50像素,因此座標與他們在第一時間拿到並在居中動畫的其餘部分繼續運行容器isent。

我最初想到的是試圖使容器的兩側和中間的高度保持居中。

我怎樣才能實現這一目標?我想一個解決方案這麼想的依賴於外部插件除了jQuery的UI.Thank您

回答

2

我想你需要根據新的寬度做的是計算你的中心是什麼/高度CSS值,然後根據這些座標的變化來翻譯框,使其看起來保持居中。我沒有時間製作js小提琴,但是您可以向動畫添加左右值。

var new_left = ($(window).width() - //final width value)/2; 
var new_top = ($(window).height() - //final height value)/2; 

,然後添加的東西動畫,如:

.animate({ 
      left:new_left, 
      top:new_top 
      }, //time interval , //method); 
+0

哇這個工作比我預期它更好地在第一次嘗試,謝謝! – parliament 2013-01-23 13:38:32