计算后的样式

一、高级浏览器和低级浏览器的不同写法

W3C制定的标准API,所有现代浏览器(包括IE9,但不包括之前的版本)都实现了window.getComputedStyle(),该方法接收一个要进行样式计算的元素,并返回一个样式对象样式对象提供了getPropertyValue()的方法,用于检索特定CSS样式属性的计算样式。getPropertyValue方法接收css属性名称,而不是驼峰式的名称。getPropertyValue()可以不写,直接用方括号来检索属性也可以

console.log(getComputedStyle(oBox)["background-color"]); //颜色计算后结果就得到rgb的值
console.log(getComputedStyle(oBox)["background-position"]);
console.log(getComputedStyle(oBox)["background-image"]);
console.log(getComputedStyle(oBox)["border-color"]);

DOM提供给JSAPI非常牛,一个元素此时的状态,完全可以被得到,好用的属性,但是不兼容。所以IE678不兼容getComputedStyle()方法,写另外一套写法:附加在元素身上的currentstyle属性,它表示和style点语法意义,使用驼峰命名法。

总结:
高级浏览器:
window.getComputedStyle(oBox).getPropertyValue("padding-left");
getComputedStyle(oBox).getPropertyValue("padding-left");
getComputedStyle(oBox)["padding-left"];

IE6/7/8
oBox.currentStyle.paddingLeft
oBox.currentStyle["paddingLeft"];

封装兼容写法:

IE678浏览器,不认识getComputedStyle视为错误

Chrome等浏览器,不认识currentStyle视为错误

只浏览器的能力。所以要进行能力检测,可以在不同浏览器中得到兼容性的写法,输出CSS属性的值。

封装一个兼容性的函数获取一个元素某个CSS属性值的方法。

API:传入两个参数,第一个是元素对象,第二个是CSS属性名

返回值是这个传入元素对象的属性值。

var oBox = document.getElementById('box');
function getStyle(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];
   }
}
alert(getStyle(oBox,"paddingLeft"));
原文地址:https://www.cnblogs.com/smivico/p/7797782.html