1. 高级浏览器和低级浏览器的不同写法
现在我们只能得到行内的样式,事实上DOM提供了可靠的API,得到计算后的样式。
W3C制定的标准API,所有现代浏览器(包括IE9,但不包括之前的版本)都实现了window.getComputedStyle(),该方法接收一个要进行样式计算的元素,并返回一个样式对象。样式对象提供了一个名为 getPropertyValue() 的方法,用于检索特定样式属性的计算样式。getPropertyValue方法接收css属性名称,而不是驼峰式的名称。getPropertyValue()可以不写,直接用方括号来检索属性也可以。
get得到,computed计算,style样式
get得到,property属性,vaule值
比如:
window.getComputedStyle(Div_box).getPropertyValue("width");
一个小知识,所有window对象的方法,都可以不用写window。
得到计算后的样式,可以直接使用 getComputedStyle 函数,而不用写window。
getComputedStyle(oDiv).getPropertyValue("width")
还要注意,引号里面不是驼峰:
getComputedStyle(oDiv).getPropertyValue("**padding-left**");
getPropertyValue可以简写:
getComputedStyle(oDiv)["padding-left"];
计算后样式是综合的结果,就是这个元素此时的状态:
现在有css:
background: url(images/songhuiqiao.jpg) no-repeat 10px 10px;
虽然没有显式指定background-position,但是有值:
getComputedStyle(oDiv)["background-position"] // 10px 10px;
DOM提供给JS的API非常牛叉,一个元素此时的状态,完完全全可以被得到。 好用的东西,一定不兼容。所以IE6、7、8不兼容getComputedStyle.getPropertyValue()的写法,另外一套写法:附加在元素身上的currentStyle属性,它表现和style点语法一样,使用驼峰式访问。
oDiv.currentStyle.width
现在要注意,它必须使用驼峰:
oDiv.currentStyle.paddingTop
IE6、7、8不能被文字撑出高,得到”auto”这个值。颜色值在高级浏览器中是rgb()格式,低级浏览器中就是原样输出。
超级无敌大坑,可以不写点语法,可以使用方括号,但是里面也要写驼峰。
oDiv.currentStyle["paddingLeft"]
总结写法:
- 高级:
window.getComputedStyle(oDiv).getPropertyValue("padding-left");
getComputedStyle(oDiv).getPropertyValue("padding-left");
getComputedStyle(oDiv)["padding-left"]; - IE6、7、8:
oDiv.currentStyle.paddingLeft;
oDiv.currentStyle["paddingLeft"];
3.2 能力检测
- IE不认识getComputedStyle视为错误
- Chrome不认识currentStyle视为错误
所以,我们现在就要进行一个兼容性写法。
if(window.getComputedStyle){
alert("我会getComputedStyle");
}else{
alert("我不会getComputedStyle")
}
所以使用能力检测,我们可以在不同浏览器中得到兼容性的写法,输出padding-left的值:
if(window.getComputedStyle){
alert(getComputedStyle(oDiv)["padding-left"]);
}else{
alert(oDiv.currentStyle.paddingLeft);
}
3. fetchComputedStyle(obj,property);
现在我们要在一个轮子,就是封装一个函数,这个函数接收两个参数,第一个是对象,第二个是属性名。
fetchComputedStyle(obj,”padding-left”);
这个函数返回的是这个属性值的计算后的样式。无论用户输入的是驼峰还是非驼峰,都能正常运行。
下例:
通过fetchComputedStyle调取getComputedStyle计算getPropertyValue属性值。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>fetchComputedStyle(obj,property)</title>
<style>
div{
padding: 10px 20px 30px;
}
</style>
</head>
<body>
<div></div>
<script type="text/javascript">
//fetchComputedStyle(oDiv,”padding-left”);
function fetchComputedStyle(obj , property){
//能力检测
if(window.getComputedStyle){
//现在要把用户输入的property中检测一下是不是驼峰,转为连字符写法
//强制把用户输入的词儿里面的大写字母,变为小写字母加-
//paddingLeft → padding-left
property = property.replace(/([A-Z])/g , function(match,$1){
return "-" + $1.toLowerCase();
});
return window.getComputedStyle(obj)[property];
}else{
//IE只认识驼峰,我们要防止用户输入短横,要把短横改为大写字母
//padding-left → paddingLeft
property = property.replace(/\-([a-z])/g , function(match,$1){
return $1.toUpperCase();
});
return obj.currentStyle[property];
}
}
var oDiv = document.getElementsByTagName("div")[0];
alert(fetchComputedStyle(oDiv,"padding-left"));
</script>
</body>
</html>