2010-10-22 84 views
0

有時我會遇到問題,試圖獲取有問題的HTML元素的大小。使用JavaScript和jQuery進行尺寸計算

我跟蹤JavaScript代碼,看看,這個元素的寬度和高度,當我做瀏覽器的控制檯中的同一段代碼返回爲0

,正確的大小返回。

實施例的代碼,演示此問題是下列:

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <meta charset="UTF-8" /> 
    <title>Decorate image with button</title> 

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" type="text/javascript"></script> 

    <script type="text/javascript" charset="utf-8"> 
     jQuery(function($){ 
      // Decorate image, wrapped to link to movie with "Play" button 
      $("a > img").each(function(){ 
       var img = $(this); 
       var a = img.parent(); 

       var w = img.width(); 
       var h = img.height(); 

       a.html(" \ 
        <table style='position: absolute;'> \ 
         <tr style='background-color:transparent;'> \ 
          <td style='width: 100%; background-color: transparent;'> \ 
           <img src='http://30ttclan.extra.hu/e107_images/RTEmagicC_play_button.png.png' style='display: block; width: 25%; margin-left:auto; margin-right: auto;'></img> \ 
          </td> \ 
         </tr> \ 
        </table>"); 
       a.append(img); 
       // Make height of table equals to height of image 
       a.find("> table").width(w); 
       a.find("> table").height(h); 
      }); 
     }); 
    </script> 
</head> 
<body> 
    <a href="http://movies.apple.com/media/us/mac/ilife/iphoto/2010/features/apple-ilife-iphoto-features_whats_new-us-20100727_r848-9cie.mov"> 
     <img src="http://kelsocartography.com/blog/wp-content/uploads/2009/01/iphoto09_map.png"> 
    </a> 
</body> 
</html> 

此代碼拍攝圖像,包裹到錨並與「播放」按鈕,必須在其上居中裝飾它。

表格單元用於居中。

在Firefox它工作得很好,但在Safari 5簡化版,

當我們追溯碼,其中「W」和「H」變量得到的寬度和高度,我們會看到,他們有零。

當我們從瀏覽器的控制檯

$("a > img").width() 

說我們會得到圖像的正確尺寸。

我想,我失去了一些東西......

我想,我一定要趕上「渲染完成」般的事件......但是,就,因爲我知道,他們是不是在DOM介紹。

我怎樣才能知道,當HTML元素呈現並顯示100%確定,我正在處理正確的大小?

+3

看起來像圖像在請求尺寸時完全加載。因此,您將使用一種機制來確保在查詢維度之前加載所有圖像。看看:http://stackoverflow.com/questions/1285375/how-to-ensure-images-are-loaded-inside-a-jquery-plugin – 2010-10-22 06:13:09

+0

令人驚歎!有用 !非常感謝,Suresh庫馬爾! :) – AntonAL 2010-10-22 06:19:12

回答

2

問題解決了。

正如在問題中提到How to ensure images are loaded inside a JQuery plugin?

WebKit瀏覽器如Chrome經常返回0大小的圖像,因爲它們是並行加載。

所有,我需要做的是對圖像使用「加載」事件。

$("a > img").load(function(){ 
    var img = $(this); 
    var a = img.parent(); 

    var w = img.width(); 
    var h = img.height(); 

    a.html(" \ 
     <table style='position: absolute;'> \ 
      <tr style='background-color:transparent;'> \ 
       <td style='width: 100%; background-color: transparent;'> \ 
        <img src='http://30ttclan.extra.hu/e107_images/RTEmagicC_play_button.png.png' style='display: block; width: 25%; margin-left:auto; margin-right: auto;'></img> \ 
       </td> \ 
      </tr> \ 
     </table>"); 
    a.append(img); 
    // Make height of table equals to height of image 
    a.find("> table").width(w); 
    a.find("> table").height(h); 
}); 

現在,我得到正確的尺寸。