2011-11-24 61 views
1

後,我在與jQuerys offset()偏移()元素的前面加上另一個元素

我有一些<img>文檔中的一個問題。在文檔準備就緒後,我將該圖像封裝到一個div中並添加一些文本。然後我需要圖像偏移。

如何在預先完成後得到圖像的偏移量?

這裏是一個示例代碼:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 

<head> 
    <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" /> 
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script> 

    <title>Image Offset Problem!?</title> 

    <script type="text/javascript"> 
     $(document).ready(function(){ 
      $img = $('#demoimg'); 

      // I hope this has nothing to do with it... it's just too big 
      $img.width(800); 

      var $prependDiv = $('<div>Some text</div>'); 
      var $wrap = $img.wrap('<div id="wrapper">').parent(); 
      //$wrap.prepend($prependDiv); 

      // Here I need to use the FINAL offset, the one with the value that shows when we click the button. 
      // Instead, I get something else! 
      var imgOffset = $img.offset(); 
      console.log('offset().top = ' + imgOffset.top); 
     }); 

    </script> 
</head> 

<body> 
    <img id="demoimg" src="demoimg.jpg" /> 
    <input type="button" value="View image offset().top" onclick="calculateOffset()" /> 
</body> 

<script type="text/javascript"> 
    function calculateOffset() { 
     console.log('offset().top = ' + $('#demoimg').offset().top); 
    }; 
</script> 

我需要訪問offset() .TOP那裏的$(document).ready()功能。

有沒有辦法做到這一點? 謝謝。

+0

我重新打開你的問題。請添加您的解決方案作爲答案。 –

回答

0

我想你需要重新定義$img包裝後使用.wrap(),因爲dom的參考已經改變。

嘗試重新選擇的元素是這樣的:

var imgOffset = $('#demoimg').offset(); 

或重新定義$img使用.wrap()後:

... 
$img = $('#demoimg'); 
var imgOffset = $img.offset(); 
... 
+0

在FF上它仍然在document.ready()上輸出13,但在按鈕上單擊28 – ieeehh

相關問題