计算后的样式window.getComputedStyle()

1.window.getComputedStyle()

1.DOM提供了可靠的api,得到计算后的样式;
2.IE9+实现了window.getComputedStyle(),获得计算后的样式;
3.该方法接受一个DOM元素,返回一个样式声明对象【CSSStyleDeclaration】,该样式对象提供了一个getPropertyValue()的方法
window.getComputedStyle[元素对象,伪类]
第二个参数选填

2.getComputedStyle与style区别

1.只读和可写

1.getComputedStyle只读,只能获取样式,不能设置样式;
2.element.style可读可写,既能获取样式,也能设置样式
  eg. 
    设置div宽度:oDiv.style.width = 100 + 'px';
    获取div宽度:oDiv.style.width 【结果: 100px;】

2.获取对象的范围

1.getComputedStyle获取的是【最终】应用到元素上的【所有】css属性对象;
2.element.style只能获取到设置在style上的样式,即只能获取元素的行内样式;

3.getComputedStyle和currentStyle区别

1.element.currentStyle()跟getComputedStyle功能类似,只是不能获取伪类的样式
2.IE6 7 8 只能使用element.currentStyle()进行获取样式

4.兼容写法

// 转化成驼峰式命名:padding-left -> paddingLeft
function toCamelCase (property) {
  return property = property.replace(/\-([a-z])/g,function(match, $1){
    return $1.toUpperCase();
  })
}

// 转化成连字符/短横线格式: paddingLeft -> padding-left
function toKebabCase (property) {
  return property = property.replace(/([A-Z])/g, function(match, $1){
    return '-' + $1.toLowerCase();
  })
}

function getCss(obj, property){
  // 兼容性检测
  if (window.getComputedStyle) {
    property = toCamelCase(property);
    return getComputedStyle(obj)[property];
  }else {
    / / IE6 7 8 转成驼峰式
    property = toCamelCase(property);
    return obj.currentStyle[property];
  }
}

5.注意

1.window.getComputedStyle(元素).getPropertyValue(样式属性)
简写:
  getComputedStyle(元素).getPropertyValue(样式属性)
  getComputedStyle(元素)[样式属性]
2.getPropertyValue(css中样式格式)中样式属性不能写驼峰格式的
  比如:
       错误: getPropertyValue('backgroundSize')
       正确:getPropertyValue('background-size')
3.getComputedStyle(元素)[随意]
  []形式既可以驼峰,也可以中横线格式
  getComputedStyle(元素)['paddingLeft']
  getComputedStyle(元素)['padding-left']
4.element.currentStyle['驼峰式写法']

你可能感兴趣的:(计算后的样式window.getComputedStyle())