2010-12-07 52 views
5

如何將div創建爲與另一個div相同的位置。jquery animate div與另一個div的位置相同

我想#DIV1的左側位置,以動畫#DIV2相同左側位置

當我使用.POSITION()。向左或.offset()。左邊得到#DIV2的左側位置,然後嘗試使#div1動畫到相同的位置,動畫運行,但它將#div1移動到與#div 2相同的位置,即#div 1的原始位置(即它們不對齊)。

下面是該腳本的簡化版本。希望你能幫助:)

<script> 
    $(function({ 
    var end = $(#div2).position().left; 
    $(#div1).animate({"left": end.left}, "slow"); 
    }); 
    </script> 

    <html> 
    <div id="div1"></div> 
    <div id="div2"></div> 
    </html> 

回答

4

嗯,我想你已經在那裏了。但是...代碼取決於您的實際佈局。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
    <head> 
    <meta http-equiv="content-type" content="text/html; charset=utf-8" /> 
     <style type="text/css"> 
      body, td, input, button{ 
       font-family: Tahoma,Verdana,Helvetica,Arial,sans-serif !important; 
       font-size:11px; 
      } 
      label{ 
       width:100px; 
       display: inline-blocK; 
      } 
      #div1{ 
       width:100px; 
       height:50px; 
       background-color:red; 
       position:absolute; 
       top:100px; 
       left:30px; 
      } 
      #div2{ 
       width:80px; 
       height:30px; 
       background-color:green; 
       position:absolute; 
       top:200px; 
       left:100px; 
      } 

     </style> 
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script> 
     <script type="text/javascript"> 
      $(function(){ 
       $("#moveitButton").click(function() { 
        doit(); 
       }) 

      }); 

      function doit() { 
       var div2Pos = $("#div2").position(); 
       var div2Width = $("#div2").css("width"); 
       var div2Height = $("#div2").css("height"); 
       $("#div1").animate({left:div2Pos.left, width:div2Width, height:div2Height}, 1000);   
      } 
     </script> 
    </head> 
    <body> 

     <div id="div1">div #1</div> 
     <div id="div2">div #2</div> 
     <button id="moveitButton">move it!</button> 
    </body> 
</html> 

(至少這部作品在我的瀏覽器)

KR,ZARA