如何在加载到html之前获取图像大小?

时间:2022-08-24 17:01:55

At first image height is coming as zero, after that by refreshing the page i am getting its actual height. I need to get its height at first time? could any body helps me?

首先,图像高度为零,然后通过刷新页面我得到它的实际高度。我需要第一次达到它的高度?任何身体可以帮助我吗?

$j(document).ready(function(){
           var imgV = new Image();
           imgV.src="http://www.kerrvilletexascvb.com/Riverside%20Nature%20Center3.JPG";
           $j("#imgD").html(imgV.height);
           alert(imgV.height);
});


<div id="imgD"></div>
<img src="http://www.kerrvilletexascvb.com/Riverside%20Nature%20Center3.JPG" />

2 个解决方案

#1


You don't have to insert an image into the DOM to get its dimensions:

您不必将图像插入DOM以获取其尺寸:

$("<img />")
    .attr("src", "http://www.google.com/intl/en_ALL/images/logo.gif")
    .load(function() {
        alert(this.width);
        alert(this.height);
    })
;

#2


The image size is only available when the image is loaded. Likely when you reload the page, the image is instantly served from cache, so its size is instantly available.

图像大小仅在加载图像时可用。可能在您重新加载页面时,图像会立即从缓存中提供,因此其大小立即可用。

If for whatever reason you need to get the size before you display an image, you can display it off-screen to begin with. Add an onload handler to it that will get called when the image is ready - you can then inspect it's size, and attach it where needed.

如果出于某种原因需要在显示图像之前获得大小,则可以在屏幕外显示该图像。添加一个onload处理程序,它将在映像准备好后调用 - 然后可以检查它的大小,并在需要的地方附加它。

By displaying off-screen, I mean stick it into a 1x1 pixel div with overflow: hidden style, somewhere on the bottom of the page.

通过显示屏幕外,我的意思是将其粘贴到1x1像素div中,溢出:隐藏式,位于页面底部的某个位置。

#1


You don't have to insert an image into the DOM to get its dimensions:

您不必将图像插入DOM以获取其尺寸:

$("<img />")
    .attr("src", "http://www.google.com/intl/en_ALL/images/logo.gif")
    .load(function() {
        alert(this.width);
        alert(this.height);
    })
;

#2


The image size is only available when the image is loaded. Likely when you reload the page, the image is instantly served from cache, so its size is instantly available.

图像大小仅在加载图像时可用。可能在您重新加载页面时,图像会立即从缓存中提供,因此其大小立即可用。

If for whatever reason you need to get the size before you display an image, you can display it off-screen to begin with. Add an onload handler to it that will get called when the image is ready - you can then inspect it's size, and attach it where needed.

如果出于某种原因需要在显示图像之前获得大小,则可以在屏幕外显示该图像。添加一个onload处理程序,它将在映像准备好后调用 - 然后可以检查它的大小,并在需要的地方附加它。

By displaying off-screen, I mean stick it into a 1x1 pixel div with overflow: hidden style, somewhere on the bottom of the page.

通过显示屏幕外,我的意思是将其粘贴到1x1像素div中,溢出:隐藏式,位于页面底部的某个位置。