html页面代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>New Web Project</title>
<style>
#div1{
width: 200px; height: 200px; background: red;
}
</style>
</head>
<body>
<div id="div1"></div>
</body>
</html>
<script>
var oDiv=document.getElementById("div1");
alert(oDiv.style.width);
</script>
oDiv.style.width获取的只能是行间样式,所以这时得到的是空。
如何获取外部样式呢
1. 使用obj.currentStyle.name
它仅适用于IE,不兼容火狐,谷歌
2. 使用 getComputedStyle(obj,null).name
它仅适用于火狐,谷歌,对IE不起作用
可以通过如下代码,对各个浏览器兼容
<script>
function getStyle(obj,name)
{
if(obj.currentStyle)
{
return (obj.currentStyle[name]);//IE
}
else
{
return (getComputedStyle(obj,null)[name]);//FireFox
}
}
window.οnlοad=function(){
var oDiv1=document.getElementById("div1");
alert(getStyle(oDiv1,"backgroundColor"));
};
</script>