getting computed style for Img width and height

Discussion in 'JavaScript' started by winterheat, Apr 22, 2008.

  1. #1
    For Firefox, we can get the computed style of an Img element, using
    the script in

    http://www.quirksmode.org/dom/getstyles.html

    so even if we set only the width of an Image in CSS, we can get both
    the width and height of the final rendered image.

    However, it won't work in IE 7.... the width will return the original
    value, but the height is "auto".... is there a way to get the final
    rendered width and height of an image in both Firefox and IE?
     
    winterheat, Apr 22, 2008 IP
  2. vpguy

    vpguy Guest

    Messages:
    275
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #2
    If you know the original height and width of the image, you can compute the adjusted height using the following formula:

    ResizedHeight = OriginalHeight * ResizedWidth / OriginalWidth;

    where:
    ResizedHeight = the height you are trying to figure out
    OriginalHeight = the original (unadjusted) height of the image
    ResizedWidth = the width of the image specified in your CSS
    OriginalWidth = the original (unadjusted) width of the image
     
    vpguy, Apr 22, 2008 IP
  3. winterheat

    winterheat Peon

    Messages:
    125
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    eh, that's right, element.offsetWidth and offsetHeight do work... and
    clientWidth, scrollWidth also work... I wonder why the later 2 are
    less known and not even in the Definitive Javascript book.
    clientWidth is more accurate width for the image as it doesn't include
    the border, if any, for the image. scrollWidth is always the same as
    offsetWidth even if i resize my window... i can't make them different.
     
    winterheat, Apr 24, 2008 IP
  4. winterheat

    winterheat Peon

    Messages:
    125
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    oh the tough part is i don't know the original width and height, as they are images from the DB. i want to resize the images so that they are confined in a 70 x 70 box, so images that are 700 x 500 will become 70 x 50, and images that are 3000 x 7000 will become 30 x 70 so there is no aspect ratio distortion.
     
    winterheat, Apr 24, 2008 IP