最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get image width and height - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Apr 28, 2009 at 20:38 GerardoGerardo 1,9484 gold badges25 silver badges34 bronze badges 0
Add a ment  | 

5 Answers 5

Reset to default 3

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.plete) {
        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./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" />

Depending on what you're after image.width or image.naturalWidth (and height equivalents) width/height gives the width/height attributes on the image tag, naturalWidth/Height gives the dimensions of the actual underlying image.

You can use img's onload to get the dimensions once the image has loaded:

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

You can try to bine 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.

发布评论

评论列表(0)

  1. 暂无评论