JQuery find image height even if it is not set in HTML

I think I have a strange problem. I run a simple query that finds the largest image on the page. Here are some test data - all 32x32 images, but one up to 300x300.

<img src="app/assets/images/icons/blue.png" />
<img src="app/assets/images/icons/error.png"/>
<img src="app/assets/images/icons/info.png" height="300" width="300"/>

If I run a simple query:

$('img').each(function(){
        console.log($(this).height());
    });

I will receive 0,0,300- and not 32,32,300.

Can someone point me to the best way to determine the size of the image you are viewing?

Thank.

+3
source share
2 answers

If the image has a size "initially", that is, there is no width or height in the HTML, you need to wait for the image to load before you know its size. I use this:

jQuery("img").each(function(){
    var img = jQuery(this);
    if (img.attr("complete")) {
        console.log(img.height());
    } else {
        img.load(function(){
            console.log(img.height());
        });
    }
});
+3

, , $(img).load(), . JavaScript:

function iLoad(isrc) {
var oImg = new Image();
oImg.src = isrc;
if (oImg.complete) {
window.alert(oImg.src + ' ' + oImg.width + ' x ' + oImg.height);
0

Source: https://habr.com/ru/post/1734712/


All Articles