Window.getComputedStyle() method returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain. Individual CSS property values are accessed through APIs provided by the object, or by indexing with CSS property names.

句法

var style = window.getComputedStyle(element [, pseudoElt]);
					
element
元素 for which to get the computed style.
pseudoElt 可选
A string specifying the pseudo-element to match. Omitted (or null ) for real elements.

返回的 style live CSSStyleDeclaration object, which updates automatically when the element's styles are changed.

抛出

TypeError
If the passed object is not an 元素 pseudoElt is not a valid pseudo-element selector or is ::part() or ::slotted() .

注意: Valid pseudo-element selector refers to syntactic validity, e.g. ::unsupported is considered valid, even though the pseudo-element itself is not supported.

范例

In this example we style a <p> element, then retrieve those styles using getComputedStyle() , and print them into the text content of the <p> .

HTML

<p>Hello</p>
					

CSS

p {
  width: 400px;
  margin: 0 auto;
  padding: 20px;
  font: 2rem/2 sans-serif;
  text-align: center;
  background: purple;
  color: white;
}
					

JavaScript

let para = document.querySelector('p');
let compStyles = window.getComputedStyle(para);
para.textContent = 'My computed font-size is ' +
    compStyles.getPropertyValue('font-size') +
    ',\nand my computed line-height is ' +
    compStyles.getPropertyValue('line-height') +
    '.';
					

结果

描述

The returned object is the same CSSStyleDeclaration type as the object returned from the element's style property. However, the two objects have different purposes:

  • The object from getComputedStyle is read-only, and should be used to inspect the element's style — including those set by a <style> element or an external stylesheet.
  • element .style object should be used to set styles on that element, or inspect styles directly added to it from JavaScript manipulation or the global style 属性。

The first argument must be an 元素 . non-elements, like a 文本 node, will throw an error.

defaultView

In many code samples, getComputedStyle is used from the document.defaultView object. In nearly all cases, this is needless, as getComputedStyle exists on the window object as well. It's likely the defaultView pattern was a combination of folks not wanting to write a testing spec for window and making an API that was also usable in Java.

Use with pseudo-elements

getComputedStyle can pull style info from pseudo-elements (such as ::after , ::before , ::marker , ::line-marker — see the pseudo-element spec ).

<style>
  h3::after {
    content: ' rocks!';
  }
</style>
<h3>Generated content</h3>
<script>
  var h3 = document.querySelector('h3');
  var result = getComputedStyle(h3, ':after').content;
  console.log('the generated content is: ', result); // returns ' rocks!'
</script>
					

注意事项

  • 返回的 CSSStyleDeclaration object contains active values for CSS property longhand names. For example, border-bottom-width 而不是 border-width and border shorthand property names . It is safest to query values with only longhand names like font-size . Shorthand names like font will not work with most browsers.
  • CSS property values may be accessed using the getPropertyValue(propName) API or by indexing directly into the object such as obj['z-index'] or obj.zIndex .
  • The values returned by getComputedStyle are resolved values . These are usually the same as CSS 2.1’s computed values , but for some older properties like width , height ,或 padding , they are instead the same as used values . Originally, CSS 2.0 defined the computed values as the "ready to be used" final values of properties after cascading and inheritance, but CSS 2.1 redefined them as pre-layout, and used values as post-layout. For CSS 2.0 properties, getComputedStyle returns the old meaning of computed values, now called used values . An example difference between pre- and post-layout values includes the resolution of percentages for width or height , as those will be replaced by their pixel equivalent only for used values .
  • Returned values are sometimes deliberately inaccurate. To avoid the “CSS History Leak” security issue, browsers may lie about the computed styles for a visited link, returning values as if the user never visited the linked URL. See Plugging the CSS History Leak and Privacy-related changes coming to CSS :visited for examples of how this is implemented.
  • During CSS 过渡 , getComputedStyle returns the original property value in Firefox, but the final property value in WebKit.
  • In Firefox, properties with the value auto return the used value, not the value auto . So if you apply top:auto and bottom:0 on an element with height:30px and a containing block of height:100px , Firefox's computed style for top 返回 70px , as 100 − 30 = 70.

规范

规范 状态 注释
CSS Object Model (CSSOM)
The definition of 'getComputedStyle()' in that specification.
工作草案
Document Object Model (DOM) Level 2 Style Specification
The definition of 'getComputedStyle()' in that specification.
过时 初始定义

浏览器兼容性

The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
getComputedStyle Chrome 1 Edge 12 Firefox 1
1
Before version 62 this function returned null when called on a Window with no presentation (e.g. an iframe with display: none; set). Since 62 it returns a CSSStyleDeclaration 对象采用 length 0, containing empty strings ( bug 1467722 ; also see bug 1471231 for further work).
IE 9 Opera 7.2 Safari 3 WebView Android 1 Chrome Android 18 Firefox Android 4
4
Before version 62 this function returned null when called on a Window with no presentation (e.g. an iframe with display: none; set). Since 62 it returns a CSSStyleDeclaration 对象采用 length 0, containing empty strings ( bug 1467722 ; also see bug 1471231 for further work).
Opera Android 10.1 Safari iOS 1 Samsung Internet Android 1.0
Pseudo-element support Chrome Yes Edge 12 Firefox Yes IE 9 Opera 15 Safari Yes WebView Android Yes Chrome Android Yes Firefox Android ? Opera Android ? Safari iOS ? Samsung Internet Android Yes

图例

完整支持

完整支持

兼容性未知 ?

兼容性未知

见实现注意事项。

另请参阅

元数据

  • 最后修改:
  1. CSS Object Model
  2. Window
  3. 特性
    1. applicationCache
    2. caches
    3. closed
    4. console
    5. controllers
    6. crossOriginIsolated
    7. crypto
    8. customElements
    9. defaultStatus
    10. devicePixelRatio
    11. dialogArguments
    12. 目录
    13. document
    14. event
    15. frameElement
    16. frames
    17. fullScreen
    18. history
    19. indexedDB
    20. innerHeight
    21. innerWidth
    22. isSecureContext
    23. isSecureContext
    24. length
    25. localStorage
    26. location
    27. locationbar
    28. menubar
    29. mozAnimationStartTime
    30. mozInnerScreenX
    31. mozInnerScreenY
    32. mozPaintCount
    33. 名称
    34. navigator
    35. onabort
    36. onafterprint
    37. onanimationcancel
    38. onanimationend
    39. onanimationiteration
    40. onappinstalled
    41. onauxclick
    42. onbeforeinstallprompt
    43. onbeforeprint
    44. onbeforeunload
    45. onblur
    46. oncancel
    47. oncanplay
    48. oncanplaythrough
    49. onchange
    50. onclick
    51. onclose
    52. oncontextmenu
    53. oncuechange
    54. ondblclick
    55. ondevicelight
    56. ondevicemotion
    57. ondeviceorientation
    58. ondeviceorientationabsolute
    59. ondeviceproximity
    60. ondragdrop
    61. ondurationchange
    62. onended
    63. onerror
    64. onfocus
    65. onformdata
    66. ongamepadconnected
    67. ongamepaddisconnected
    68. ongotpointercapture
    69. onhashchange
    70. oninput
    71. oninvalid
    72. onkeydown
    73. onkeypress
    74. onkeyup
    75. onlanguagechange
    76. onload
    77. onloadeddata
    78. onloadedmetadata
    79. onloadend
    80. onloadstart
    81. onlostpointercapture
    82. onmessage
    83. onmessageerror
    84. onmousedown
    85. onmouseenter
    86. onmouseleave
    87. onmousemove
    88. onmouseout
    89. onmouseover
    90. onmouseup
    91. onmozbeforepaint
    92. onpaint
    93. onpause
    94. onplay
    95. onplaying
    96. onpointercancel
    97. onpointerdown
    98. onpointerenter
    99. onpointerleave
    100. onpointermove
    101. onpointerout
    102. onpointerover
    103. onpointerup
    104. onpopstate
    105. onrejectionhandled
    106. onreset
    107. onresize
    108. onscroll
    109. onselect
    110. onselectionchange
    111. onselectstart
    112. onstorage
    113. onsubmit
    114. ontouchcancel
    115. ontouchstart
    116. ontransitioncancel
    117. ontransitionend
    118. onunhandledrejection
    119. onunload
    120. onuserproximity
    121. onvrdisplayactivate
    122. onvrdisplayblur
    123. onvrdisplayconnect
    124. onvrdisplaydeactivate
    125. onvrdisplaydisconnect
    126. onvrdisplayfocus
    127. onvrdisplaypointerrestricted
    128. onvrdisplaypointerunrestricted
    129. onvrdisplaypresentchange
    130. onwheel
    131. opener
    132. origin
    133. outerHeight
    134. outerWidth
    135. pageXOffset
    136. pageYOffset
    137. parent
    138. 性能
    139. personalbar
    140. pkcs11
    141. screen
    142. screenLeft
    143. screenTop
    144. screenX
    145. screenY
    146. scrollbars
    147. scrollMaxX
    148. scrollMaxY
    149. scrollX
    150. scrollY
    151. self
    152. sessionStorage
    153. sidebar
    154. speechSynthesis
    155. status
    156. statusbar
    157. toolbar
    158. top
    159. visualViewport
    160. window
  4. 方法
    1. alert()
    2. atob()
    3. back()
    4. blur()
    5. btoa()
    6. cancelAnimationFrame()
    7. cancelIdleCallback()
    8. captureEvents()
    9. clearImmediate()
    10. clearInterval()
    11. clearTimeout()
    12. close()
    13. confirm()
    14. convertPointFromNodeToPage()
    15. convertPointFromPageToNode
    16. createImageBitmap()
    17. dump()
    18. fetch()
    19. find()
    20. focus()
    21. forward()
    22. getAttention()
    23. getComputedStyle()
    24. getDefaultComputedStyle()
    25. getSelection()
    26. home()
    27. matchMedia()
    28. minimize()
    29. moveBy()
    30. moveTo()
    31. open()
    32. openDialog()
    33. postMessage()
    34. print()
    35. prompt()
    36. queueMicrotask()
    37. releaseEvents()
    38. requestAnimationFrame()
    39. requestFileSystem()
    40. requestIdleCallback()
    41. resizeBy()
    42. resizeTo()
    43. restore()
    44. routeEvent()
    45. scroll()
    46. scrollBy()
    47. scrollByLines()
    48. scrollByPages()
    49. scrollTo()
    50. setCursor()
    51. setImmediate()
    52. setInterval()
    53. setTimeout()
    54. showModalDialog()
    55. sizeToContent()
    56. stop()
    57. updateCommands()
  5. 事件
    1. event
    2. afterprint
    3. animationcancel
    4. animationend
    5. animationiteration
    6. beforeprint
    7. beforeunload
    8. blur
    9. copy
    10. cut
    11. DOMContentLoaded
    12. error
    13. focus
    14. hashchange
    15. languagechange
    16. load
    17. message
    18. messageerror
    19. offline
    20. online
    21. orientationchange
    22. pagehide
    23. pageshow
    24. paste
    25. popstate
    26. rejectionhandled
    27. storage
    28. transitioncancel
    29. unhandledrejection
    30. unload
    31. vrdisplayconnect
    32. vrdisplaydisconnect
    33. vrdisplaypresentchange
  6. Related pages for CSSOM
    1. AnimationEvent
    2. CSS
    3. CSSConditionRule
    4. CSSGroupingRule
    5. CSSKeyframeRule
    6. CSSKeyframesRule
    7. CSSMediaRule
    8. CSSNamespaceRule
    9. CSSPageRule
    10. CSSRule
    11. CSSRuleList
    12. CSSStyleDeclaration
    13. CSSStyleRule
    14. CSSStyleSheet
    15. CSSSupportsRule
    16. CaretPosition
    17. LinkStyle
    18. MediaQueryList
    19. MediaQueryListListener
    20. Screen
    21. StyleSheet
    22. StyleSheetList
    23. TransitionEvent