Skip to content

Window

[TOC]

索引

Window

实例属性

document【

history【

indexedDB【

localStorage【

location【

opener【

performance【

screen【

实例方法

定时器

setTimeout()【
setInterval()【
clearTimeout()【
clearInterval()【

窗口

open()【
close()【

网络请求

fetch()【

CSS样式

getComputedStyle()

window.getComputedStyle()(element,pseudoElt?),用于获取元素最终应用的 计算样式

  • elementElement,要获取样式的 DOM 元素。

  • pseudoElt?string默认:null,指定要匹配的伪元素选择器字符串,如:hover::after

  • 返回:

  • styleCSSStyleDeclaration,包含元素所有计算后的 CSS 属性值。

  • 特性:

    • 计算值vs解析值
      • 返回的值是计算值如 width: 100px,而非 CSS 原始值如 width: 50%
      • 单位统一转换为绝对单位如 rem → pxrgb() → rgba()
    • 只读性:CSSStyleDeclaration 对象是只读的,无法直接修改样式。
    • 触发reflow:调用 getComputedStyle() 可能触发浏览器重排(reflow),频繁使用可能影响性能。
    • 元素必须已渲染:若元素未插入 DOM 树如display: none,某些样式可能返回 auto 或 0px。
    • 伪元素限制:伪元素需在 CSS 中明确定义,如 element::before { content: "" },否则返回空值。
    • 兼容性替代:IE8及以下不支持,可用 element.currentStyle 替代。
    • 属性访问:优先使用 getPropertyValue() 访问计算后样式的属性,兼容性更好。
  • 常见用途:

    • 获取元素的计算样式

      js
      const element = document.getElementById('myElement');
      const styles = window.getComputedStyle(element);
      
      // 获取具体属性值
      const width = styles.getPropertyValue('width');     // 如 "100px"
      const color = styles.getPropertyValue('color');     // 如 "rgb(255, 0, 0)"
      const fontSize = styles.fontSize;                   // 直接访问属性
    • 获取伪元素的样式

      js
      const button = document.querySelector('button');
      const hoverStyles = getComputedStyle(button, ':hover');
      const backgroundColor = hoverStyles.backgroundColor; // 悬停时的背景色
    • 对比内联样式

      js
      // 内联样式(仅包含 style 属性直接设置的样式)
      const inlineWidth = element.style.width;
      
      // 计算样式(包含所有来源的最终值)
      const computedWidth = getComputedStyle(element).width;

帧动画

requestAnimationFrame()【
cancelAnimationFrame()【

事件

基础事件

resize【

剪切板事件

copy【
cut【
paste【

网络链接事件

online【
offline【

聚焦事件

focus【
blur【

历史记录事件

hashchange【
popstate【
pageshow【
pagehide【

加载事件

load【