简体   繁体   中英

Getting height of scaled image

I'm getting original sizes of an image. There is css applied to an image via max-width:473px; and height is resized automatically by the browser. But inside image load event i'm getting original, non-scaled sizes.

So basically original image sizes were 506x337 and after css rule image becomes 473x315 . How do i get 315px height inside load event ?

Update

There is the snippet for testing: http://jsfiddle.net/CXNan/

This will give you the computed height of your element as I posted in the comment @ Question.

window.getComputedStyle(document.getElementById("idOfYourImage"), null).getPropertyValue("height")

As you guys already noted, isn't cross-browser (aka not IE or old stuff).


Update

I've found this getComputedStyle for IE but couldn't test it yet. Might be okay because as http://ie.microsoft.com/testdrive/HTML5/getComputedStyle/ says, the older IE API was called currentStyle , which this "getComputedStyle for IE" uses.

The only problem for the currentStyle is that getComputedStyle will always return a pixel value if possible while currentStyle returns the raw value (so width:50% on css will return 50%, not the pixel size of 50% of the parent).

Divide the max width by the aspect ratio and you will get the scaled height. Note that if the image is less than the max width, no scaling will be done. Something like this:

var height = img.width > 473 ? 473 / (img.width/img.height) : img.height;

You can also use

this.offsetHeight

see the fiddle . It contains read-only pixel size, see the reference . It is supported in MSIE and should be cross-browser reliable.

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