开发者

Is there anyway to use javascript get the attributes determined by CSS?

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{
    开发者_如何学C  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?


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.


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.


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.


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];
};


This is my cross-browser inline function:

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜