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
可选
null
) for real elements.
返回的
style
是
live
CSSStyleDeclaration
object, which updates automatically when the element's styles are changed.
TypeError
元素
或
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>
.
<p>Hello</p>
p {
width: 400px;
margin: 0 auto;
padding: 20px;
font: 2rem/2 sans-serif;
text-align: center;
background: purple;
color: white;
}
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:
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.
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.
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.
getPropertyValue(propName)
API or by indexing directly into the object such as
obj['z-index']
or
obj.zIndex
.
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
.
getComputedStyle
returns the original property value in Firefox, but the final property value in WebKit.
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.
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
getComputedStyle
|
Chrome 1 | Edge 12 |
Firefox
1
|
IE 9 | Opera 7.2 | Safari 3 | WebView Android 1 | Chrome Android 18 |
Firefox Android
4
|
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 |
完整支持
兼容性未知
见实现注意事项。
Window
applicationCache
caches
closed
console
controllers
crossOriginIsolated
crypto
customElements
defaultStatus
devicePixelRatio
dialogArguments
目录
document
event
frameElement
frames
fullScreen
history
indexedDB
innerHeight
innerWidth
isSecureContext
isSecureContext
length
localStorage
location
locationbar
menubar
mozAnimationStartTime
mozInnerScreenX
mozInnerScreenY
mozPaintCount
名称
navigator
onabort
onafterprint
onanimationcancel
onanimationend
onanimationiteration
onappinstalled
onauxclick
onbeforeinstallprompt
onbeforeprint
onbeforeunload
onblur
oncancel
oncanplay
oncanplaythrough
onchange
onclick
onclose
oncontextmenu
oncuechange
ondblclick
ondevicelight
ondevicemotion
ondeviceorientation
ondeviceorientationabsolute
ondeviceproximity
ondragdrop
ondurationchange
onended
onerror
onfocus
onformdata
ongamepadconnected
ongamepaddisconnected
ongotpointercapture
onhashchange
oninput
oninvalid
onkeydown
onkeypress
onkeyup
onlanguagechange
onload
onloadeddata
onloadedmetadata
onloadend
onloadstart
onlostpointercapture
onmessage
onmessageerror
onmousedown
onmouseenter
onmouseleave
onmousemove
onmouseout
onmouseover
onmouseup
onmozbeforepaint
onpaint
onpause
onplay
onplaying
onpointercancel
onpointerdown
onpointerenter
onpointerleave
onpointermove
onpointerout
onpointerover
onpointerup
onpopstate
onrejectionhandled
onreset
onresize
onscroll
onselect
onselectionchange
onselectstart
onstorage
onsubmit
ontouchcancel
ontouchstart
ontransitioncancel
ontransitionend
onunhandledrejection
onunload
onuserproximity
onvrdisplayactivate
onvrdisplayblur
onvrdisplayconnect
onvrdisplaydeactivate
onvrdisplaydisconnect
onvrdisplayfocus
onvrdisplaypointerrestricted
onvrdisplaypointerunrestricted
onvrdisplaypresentchange
onwheel
opener
origin
outerHeight
outerWidth
pageXOffset
pageYOffset
parent
性能
personalbar
pkcs11
screen
screenLeft
screenTop
screenX
screenY
scrollbars
scrollMaxX
scrollMaxY
scrollX
scrollY
self
sessionStorage
sidebar
speechSynthesis
status
statusbar
toolbar
top
visualViewport
window
alert()
atob()
back()
blur()
btoa()
cancelAnimationFrame()
cancelIdleCallback()
captureEvents()
clearImmediate()
clearInterval()
clearTimeout()
close()
confirm()
convertPointFromNodeToPage()
convertPointFromPageToNode
createImageBitmap()
dump()
fetch()
find()
focus()
forward()
getAttention()
getComputedStyle()
getDefaultComputedStyle()
getSelection()
home()
matchMedia()
minimize()
moveBy()
moveTo()
open()
openDialog()
postMessage()
print()
prompt()
queueMicrotask()
releaseEvents()
requestAnimationFrame()
requestFileSystem()
requestIdleCallback()
resizeBy()
resizeTo()
restore()
routeEvent()
scroll()
scrollBy()
scrollByLines()
scrollByPages()
scrollTo()
setCursor()
setImmediate()
setInterval()
setTimeout()
showModalDialog()
sizeToContent()
stop()
updateCommands()
event
afterprint
animationcancel
animationend
animationiteration
beforeprint
beforeunload
blur
copy
cut
DOMContentLoaded
error
focus
hashchange
languagechange
load
message
messageerror
offline
online
orientationchange
pagehide
pageshow
paste
popstate
rejectionhandled
storage
transitioncancel
unhandledrejection
unload
vrdisplayconnect
vrdisplaydisconnect
vrdisplaypresentchange
AnimationEvent
CSS
CSSConditionRule
CSSGroupingRule
CSSKeyframeRule
CSSKeyframesRule
CSSMediaRule
CSSNamespaceRule
CSSPageRule
CSSRule
CSSRuleList
CSSStyleDeclaration
CSSStyleRule
CSSStyleSheet
CSSSupportsRule
CaretPosition
LinkStyle
MediaQueryList
MediaQueryListListener
Screen
StyleSheet
StyleSheetList
TransitionEvent