如下:
#div1{
width:100px;
}
<div id="div1"></div>
如果想通过document.getElementById("div1").style.width来获取是不成功的。必须写inline css
但是line css往往不符合要求,并没有将结构与表现分离
所以要用js来或取最终样式,如获取width
dom:
document.defaultView.getComputedStyle(obj, null).width;
ie:
obj.currentStyle.width;
整个例子:
Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Computed Style Example</title>
<style type="text/css">
div.special{
margin-top:10px;
width:200px;
height:10px;
background:aqua;
}
</style>
</head>
<body>
<div>
<div id="div1" class="special"></div>
<input type="button" value="Get Background Color" onclick="javascript:alert(getFinallyStyle('div1', 'width'))" />
</div>
<script type="text/javascript">
//<![CDATA[
function getFinallyStyle(sElementId, sAttribute) {
var oElement = document.getElementById(sElementId);
return !!document.defaultView ? eval("document.defaultView.getComputedStyle(oElement, null)." + sAttribute) :
eval("oElement.currentStyle." + sAttribute);
}
//]]>
</script>
</body>
</html>