一般来说我们获取CSS的样式的时候会优先采用Elment.style.cssName 这种方法,这种方法类似于对象设置get,set属性获取,例如Elment.style.cssName是获取,Elment.style.cssName = “100px” 是设置,但是这种方法不能获取css样式表或者内嵌样式(这种方法只能获取内联样式),所以这个时候我们需要其他方法。
DOM标准为我们提供了window.getComputedStyle这个方法可以用来获取css样式表和内嵌样式的计算值,这个方法接受2个参数,并且返回一个样式表对象,对象的命名采用驼峰式的命名规则
widow.getComputedStyle(element,null)其中第二个参数一般为null,也可以是伪类例如:hover,:after设置过后就是获取伪类上设置的样式,注意这个方法返回了一个对象,我们要从对象上获取我们所需要的样式。例如:
widow.getComputedStyle(element,null).backgroundColor
IE为我们提供了另一种方法currentStyle,使用方法为element.currentStyle,它也返回一种样式表对象,查询方式也是element.currentStyle.backgroundColor,这个方法无法获取我们在样式表中设置的伪类元素。
这2种方法获取计算样式并不是万能的,在不同的浏览器下会有很大的差别,所以使用的时候要小心,比如在IE下获取未设置的元素会返回auto,或者其它值。以下是对这2种方法的封装
var css = (function (model) {
if (window.getComputedStyle){
return function css (cssName,cssValue,that) {
if(typeof cssValue !== "string") {
that = cssValue;
}
if (typeof that === "undefined"){
that = this;
}
if (typeof cssName === "string") {
if (typeof cssValue === "string") {
return that.style[cssName] = cssValue;
}
if (that.style[cssName]) {
return that.style[cssName];
}else{
var cssStyle = window.getComputedStyle(that,null);
return cssStyle[cssName];
}
}
if (typeof cssName === "object") {
for (var i in cssName) {
that.style[i] = cssName[i];
}
return cssName;
}
}
}else{
return function css (cssName,cssValue,that) {
if(typeof cssValue !== "string") {
that = cssValue;
}
if (typeof that === "undefined"){
that = this;
}
if (typeof cssName === "string") {
if (typeof cssValue === "string") {
return that.style[cssName] = cssValue;
}
if (that.style[cssName]) {
return that.style[cssName];
}else{
var cssStyle = that.currentStyle;
return cssStyle[cssName];
}
}
if (typeof cssName === "object") {
for (var i in cssName) {
that.style[i] = cssName[i];
}
return cssName;
}
}
}
})();