0

For example,

<html>
  <head><link rel="stylesheet" type="text/css" href="theme.css"></head>
    <body>
      <img id="tmp"></img>
    </body>
</html>

in theme.css

img#tmp{
      width:120px;
      top:0;
      left:0;
      }

Is there anyway that I can get the width of the image "tmp" directly by JavaScript? Something like
var temp=document.getElementById("tmp"); var width=temp.style.width?

Fan Wu
  • 169
  • 2
  • 11
  • Duplicate http://stackoverflow.com/questions/623172/how-to-get-image-size-height-width-using-javascript – Ray Toal Aug 16 '11 at 01:21

6 Answers6

0

You'll definitely want JQuery's help on this. Here is the list of all JQuery functions that can help you access all the style information you would want (hopefully).

Btw, if you're not familiar with some sort of Javascript library, it's probably a good idea to learn one.

Nadir Muzaffar
  • 4,772
  • 2
  • 32
  • 48
0

I 2nd Nadir's motion, however in your direct example you can change your code to:

var temp=document.getElementById("tmp");
var width=temp.style.width;

In your own example, you have used the getElementById incorrectly by pluralizing it.

This comment sums up why.

danjah
  • 2,939
  • 2
  • 30
  • 47
  • @Danjah This will only work if the `width` property was set inline (inside the `style` attribute), which is *not* the case with OP's question. – Šime Vidas Aug 16 '11 at 01:31
0

What you're after is the computed style of the element. As usual, IE6-8 does it differently, so we need to do some sniffing:

var getStyle = window.getComputedStyle ? function (elem, prop) {
    var styles = getComputedStyle(elem, null);
    return prop ? styles[prop] : styles;
} : function (elem, prop) {
    return prop ? elem.currentStyle : elem.currentStyle[prop];
};
sdleihssirhc
  • 42,000
  • 6
  • 53
  • 67
0

Here you go:

getComputedStyle( elem ).getPropertyValue( 'width' )

where elem is the DOM element.

Live demo: http://jsfiddle.net/7h4cg/

Btw, some older versions of some browsers do not support this code. If you need a cross-browser solution, use a cross-browser library.

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
0

This is my cross-browser inline function:

function getComputedStyle(elem, styleAttr){
    return (elem.currentStyle ? elem.currentStyle : document.defaultView.getComputedStyle(elem, null))[styleAttr];
}
Alex
  • 180
  • 4
0

Some browsers will return the literal style width and height, as it was written in the css- pehaps as a pecentage or an em multiple, while others translate all style dimensions to pixels.

In this case, I'd use document.getElementById('tmp').offsetWidth to be sure to get the rendered width in pixels, no matter how it was assigned.

kennebec
  • 102,654
  • 32
  • 106
  • 127