原生的JavaScript获取写在标签内部的样式很简单:
<div class="test" id="test" style="100px;">test</div> <script type="text/javascript"> window.onload=function(){ var oTest=document.getElementById("test"); alert(oTest.style.width); //100px } </script>
对于外部样式 与 嵌入式样式,JavaScript通过style.width没有办法获取到宽度,解决办法:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <style type="text/css"> .test{ width:100px; height:100px; border:5px solid #ddd; padding:20px; font-family:Arial, Helvetica, sans-serif; font-size:24px;} </style> <script type="text/javascript"> window.onload=function(){ var oTest=document.getElementById("test"); /*var styleInfo=window.getComputedStyle ?window.getComputedStyle(oTest,null):window.currentStyle;*/ function getStyle(ele,name){ var styleInfo; if(window.getComputedStyle){ //非ie styleInfo=window.getComputedStyle(ele,false)[name]; }else{ //ie opera styleInfo=window.currentStyle[name]; } return styleInfo; } alert(getStyle(oTest,"width")); } </script> </head> <body> <div class="test" id="test" style="">test</div> </body> </html>
相关连接: