2012-12-07 35 views
5

我在我的JavaScript代碼中附加了圖像,但想要獲取其正確的寬度和高度。這可能嗎?我的代碼如下所示:獲取使用JavaScript加載的圖像的寬度

$('body').append('<img src="path.jpg" width="' 
     + w + '" height="' + h + '" alt="" />'); 

我知道它已經被加載後如何獲得圖像的寬度,但我加載一個img,而想直接獲得其相應的寬度和高度。有小費嗎?

回答

1

HTML規範建議爲<img>指定heightwidth作爲視覺劑的暗示,這混合的標記和樣式規則構建HTML文檔的可視化表示。在CSS框模型中,圖像尺寸是內在的,即它們隱含在二進制blob中。這意味着瀏覽器必須等待HTTP響應,然後才能確定圖像的大小,從而確定如何佈置和定位兄弟和父母。在HTML頁面中指定尺寸有助於瀏覽器快速渲染頁面,因爲它可以在從服務器下載圖像之前指定寬度和高度。

此時應該清楚,在下載之前,無法訪問客戶端上的圖像寬度。當Javascript知道它時,瀏覽器已經知道了,並且您表示對於您的要求來說已經太遲了。

所以提示瀏覽器的唯一選擇是測量服務器端的圖像。它可以在每個請求的基礎上完成(但是這浪費了資源),或者可以在圖像第一次上傳(然後從數據庫中檢索)時完成一次,或者最終可以假定它是不變的,例如如果這是個人資料圖片,您的服務總是會增長或縮小至像素大(這可能是一個配置參數)。

+0

謝謝,我擔心這是問題所在。所以剩下的一個選項是將圖像預加載到緩存中,但將其隱藏並顯示出來?我想我會在上傳圖片時給出參數,這似乎更好,然後預加載圖像。 – adnan

+0

如果在未加載時使其不可見,則設置尺寸沒有意義,因爲瀏覽器必須重新佈局。唯一的選擇是在服務器上進行測量,但請注意,這不是要求,也不是常用的做法。如果你真的想要,那沒關係,否則就跳過它 – Raffaele

+0

謝謝,那就像這樣:http://stackoverflow.com/questions/1944280/determine-original-size-of-image-cross-browser。但是我現在要在上傳的文件上傳時自動添加參數 – adnan

3

加載它後,可以得到圖像的大小:

var imageWidth; 
var imageHeight; 
$('<img>').on('load', function(){ 
    imageWidth = this.width; 
    imageHeight = this.height; 
    $('body').append($(this)); 
}).attr('src', imageUrl); 
0
var image = new Image; 
image.src = $('img').prop('src'); 
alert($(image).prop('height')) 
0

您可以提前加載圖像,而不必立即顯示圖像。

var img = document.createElement('img'); 
img.src = 'your_image.jpg'; 
var imgHeight = img.height, 
    imgWidth = img.width; 

無論何時,只要您需要,您現在可以將它與正確的細節一起調用。

+0

您必須等到圖像加載後才能獲取它的大小。您的代碼不適用於加載速度較慢的圖像。 – gabitzish

0

我決定在WordPress的輸出圖像尺寸創建一個新的功能,所以我可以檢索與WordPress

function wpsc_the_product_dimensions($width='', $height='', $product_id='') { 
    if (empty($product_id)) 
     $product_id = get_the_ID(); 


    $product = get_post($product_id); 

    if ($product->post_parent > 0) 
     $product_id = $product->post_parent; 

    $attached_images = (array)get_posts(array(
       'post_type' => 'attachment', 
       'numberposts' => 1, 
       'post_status' => null, 
       'post_parent' => $product_id, 
       'orderby' => 'menu_order', 
       'order' => 'ASC' 
      )); 


    $post_thumbnail_id = get_post_thumbnail_id($product_id); 

    $image_attributes = wp_get_attachment_image_src($post_thumbnail_id, 'large'); 

    $image_dimensions = 'product-link="'.$image_attributes[0].'" product-width="'.$image_attributes[1].'" product-height="'.$image_attributes[2].'"'; 

    return $image_dimensions; 
} 

不和附加image_dimensions到IMG和檢索不使用javascript

w = $(this).attr('product-width'); 
h = $(this).attr('product-height'); 
相關問題