今天工作的时候遇到了这个问题,直接通过style.属性获取是不能行的
使用Javascript获取元素CSS属性值
对于元素的内联CSS样式(<div style="color:#369">hello</div>),可以直接使用element.style.color来直接获取css属性的值,但是对于外部定义的css样式使用这种方式就无法获取了,而且IE浏览器和其他标准浏览器(Firefox,Chrome,Opera,Safari)使用的方法不一样,IE浏览器使用element.currentStyle,W3C标准浏览器使用getComputedStyle来获取。
IE获取元素外部定义的CSS属性值:
element.currentStyle
currentStyle对象返回了元素上的样式表,但是style对象只返回通过style标签属性应用到元素的内嵌样式。因此,通过currentStyle对象获取的样式值可能与通过style对象获取的样式值不同。例如,如果段落的color属性值通过链接或嵌入样式表设置为红色( red ),而不是内嵌的话,对象.currentStyle.color 将返回正确的颜色,而对象style.color不能返回值。但是,如果用户指定了 <P STYLE="color:’red’">,currentStyle和STYLE对象都将返回值 red。
currentStyle对象反映了样式表中的样式优先顺序。在 HTML 中此顺序为:
1) 内嵌样式
2) 样式表规则
3) HTML 标签属性
4) HTML 标签的内部定义
例子如下:
<!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>
.view{
background-color:red;
width:400px;
height:400px;
text-align:center;}
</style>
<script>
// 元素 , 属性
function getCurrentStyle(element,prop){
if(element.currentStyle){ //IE
return element.currentStyle[prop];
}else if(window.getComputedStyle){ //w3c标准
prop = prop.replace(/([A-Z])/g, "-$1");
prop = prop.toLowerCase(); //转小写
return getComputedStyle(element,false)[prop];
}
}
window.οnlοad=function(){
var school=document.getElementById("school");
var width=getCurrentStyle(school,"width");
alert(width);
}
</script>
</head>
<body>
<div id="school" class="view"></div>
</body>
</html>