window.getComputedStyle可获取 伪类元素 样式 window.getComputedStyle详解 window.getComputedStyle说明:getComputedStyle()返回元素的所有CSS属性的计算值语法:var style = window.getComputedStyle(element[, pseudoElt]);参数说明:element:目标元素的DOM对象pseudoElt:指明要匹配的伪元素,对于普通元素必须指定为null(或省略)(or not specified翻译成省略不知道有没有问题,不过测试结果表明对于普通元素确实可以省略该参数)返回值style为CSSStyleDeclaration对象.注意:Gecko2.0(Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1)之前的版本中pseudoElt参数是必需的.对于其它主流的浏览器而言,若该参数指定为null,则可以省略.Gecko后来也改成和其它浏

window.getComputedStyle

说明:
getComputedStyle()返回元素的所有CSS属性的计算值

语法:
var style = window.getComputedStyle(element[, pseudoElt]);

参数说明:
element:目标元素的DOM对象
pseudoElt:指明要匹配的伪元素,对于普通元素必须指定为null(或省略)(or not specified翻译成省略不知道有没有问题,不过测试结果表明对于普通元素确实可以省略该参数)

返回值style为CSSStyleDeclaration对象.

注意:Gecko2.0(Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1)之前的版本中pseudoElt参数是必需的.对于其它主流的浏览器而言,若该参数指定为null,则可以省略.Gecko后来也改成和其它浏览器保持一致.

测试:
<a href="#" >官方文档里有一段关于getComputedStyle()与元素的style属性的区别


Description

The returned object is of the same type that the object returned from the element's style property, however the two objects have different purpose. The object returned from getComputedStyle is read-only and can be used to inspect the element's style (including those set by a <style> element or an external stylesheet). The elt.style object should be used to set styles on a specific element.

这段话只是说明getComputedStyle获取的值是只读的并且可被用于检测元素的样式(包括style属性和外部样式).而elt.style可被用于设置指定元素的样式.

chrome为例查看getComputedStyle()与元素的style属性的区别,请注意其中cssText属性的区别
<a href="#" >直接给出官方的Demo:
<style>
 h3:after {
   content: ' rocks!';
 }
</style>

<h3>generated content</h3> 

<script>
  var  h3  = document.querySelector('h3'), 
         result   = getComputedStyle(h3, ':after').content;

  console.log('the generated content is: ', result); // returns ' rocks!'
</script>