简体   繁体   中英

Get image width and height

I need to get an image's dimensions in javascript (jQuery) when no styles are specified for it (jQuery's css() returns 0).

Maybe it is because I'm loading the image with jQuery just before asking for its dimensions. If this is the case, is there any event to listen that tells when the image has been loaded?

Maybe the image has not fully loaded therefore the dimensions can not be given.But without your code I can't tell what you're doing wrong, but here is an Example that would work:

function LoadImage(isrc) {
    var oImg = new Image();
    oImg.src = isrc;
    if (oImg.complete) {
        window.alert(oImg.src + ' ' + oImg.width + ' x ' + oImg.height);
    }
    else {
        window.setTimeout('iLoad(imgsrc)', 1000);
    }
}

<body onLoad='LoadImage(imgsrc)'>

here's a link that helps, look at the demo: http://docs.jquery.com/Events/load

with jquery there is a load() event that's fired when an image is done loading ie:

<script type="text/javascript">
    $(document).ready(function()
    {
        $('#theImage').load(function()
        {
            // do the stuff here.
        });
    });
</script>


<img src="blah.jpg" id="theImage" />

根据您在 image.width 或 image.naturalWidth(和高度等价物)之后的内容,width/height 给出了图像标签上的宽度/高度属性,naturalWidth/Height 给出了实际底层图像的尺寸。

加载图像后,您可以使用img 的 onload获取尺寸:

<img src="..." onload="getDimensions(this)" />

You can try to combine karim79 's and John Boker 's answer. Try to preload the image into hidden DOM and when it loads you can try to get its width&height.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM