2012-05-14 21 views
1

我想加載html,然後得到真實的圖像高度。如何使用JQuery獲得真正的圖像高度?

$("#cover").html(stuff); //this has the image inside it 
$(function(){ 
    console.log($("#cover img").height()); //sometimes it's 0 
}); 

出於某種原因,高度爲0,有時難道是因爲圖像沒有被完全加載的是,和JQuery視其爲0?如果是這樣,我該如何克服這一點?圖像加載時是否有回調或什麼?

+0

您的圖像是否有'none'的顯示? –

回答

3

可以使用.load jQuery的

$('#cover').html(stuff); 
$('#cover img').load(function() { 
    console.log($(this).height()); 
}; 
0
//locate the image(s) 
$("#cover img").each(function(){ 

    //Build a new Image Object outside the DOM 
    //that way, CSS won't affect it 
    var img = new Image(); 

    //add a callback when loaded 
    img.onload = function(){ 
     //your width and height 
     //img.width 
     //img.height 
    } 

    //use the image src to load 
    //use attr() to resolve path issues across browsers 
    img.src = $(this).attr('src'); 

}); 
1

()方法爲什麼做的console.log匿名函數裏面?你試過這個嗎?

$("#cover").html(stuff); //this has the image inside it 
console.log($("#cover img").height()); 
+0

JamesOR的回答比較好。 – CognitiveCarbon

0

嘗試使用load method方法,我們可以充分利用,使這項工作,我們希望它太的方式。

我們現在面臨的問題是,在Webkit瀏覽器中,當DOM已準備就緒並且DOM已準備好加載圖像之前,jQuery代碼就會運行。所以代碼運行,但由於沒有圖像可以獲得寬度,因此圖像寬度爲0。我們可以使用load方法讓代碼等待,直到窗口完全加載後才運行。

$(window).load(function() { 
      console.log($("#cover img").height()); 
}); 
0

嘗試使用ATTR()來獲得高度: -

$("#yourElemengtID").attr('height') 
0

這裏是一塊小的代碼我希望使用此之前將幫助您
在我的顯示圖像時,鼠標在調用這個函數

function MouseIn() 
     { 
      var src; 
      //to get original image size 
      var img =$(this);// displayed image 
      var theImage = new Image();// create a cache image 
      var imgsource =img.attr("src");// take the src of displayed image 
      theImage.src = imgsource;// give cached image the source of displayed image 
      var original_height = theImage.height// take height of image from the source 
      var original_width = theImage.width;//take width of image from the source 

      // to get the displayed image size 
      var Image_displaysize_width= img.width(); 
      var Image_displaysize_height= img.height(); 
     } 
0

不要你的意思是做這樣的事情?

jQuery("#myImg")[0].naturalHeight 

更好的是,儘可能不要使用jQuery的開銷。

document.getElementById('myImg').naturalHeight 
相關問題