ZetCode

JavaScript getComputedStyle

最后修改于 2025 年 4 月 2 日

在本文中,我们将探讨 JavaScript 中的 window.getComputedStyle 方法。此方法对于访问 DOM 元素的计算后 CSS 样式至关重要,包括来自样式表和内联样式的样式。

基本定义

window.getComputedStyle 方法返回一个对象,其中包含元素的所有 CSS 属性,这些属性是从样式表和内联样式计算得出的。它提供了浏览器用于渲染元素的最终值。

与仅返回内联样式的 element.style 不同,getComputedStyle 返回所有影响元素的样式。这包括默认浏览器样式和 CSS 规则中的样式。

基本的 getComputedStyle

此示例演示了如何访问简单 div 元素的计算后样式。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Basic getComputedStyle</title>
    <style>
        #myDiv {
            width: 200px;
            height: 100px;
            background-color: lightblue;
            padding: 10px;
        }
    </style>
</head>
<body>

<div id="myDiv">Sample Content</div>

<script>
    const div = document.getElementById('myDiv');
    const styles = window.getComputedStyle(div);
    
    console.log('Background color:', styles.backgroundColor);
    console.log('Width:', styles.width);
    console.log('Height:', styles.height);
    console.log('Padding:', styles.padding);
</script>

</body>
</html>

在这个基本示例中,我们有一个带样式的 div 元素。JavaScript 代码使用 getComputedStyle 来访问 div 的所有计算后 CSS 属性。

该方法返回一个 CSSStyleDeclaration 对象,其中包含所有计算后样式。然后我们将几个样式属性记录到控制台。请注意,返回值是其计算后的形式(例如,“rgb(173, 216, 230)”)。

访问伪元素样式

此示例展示了如何使用 getComputedStyle 访问伪元素的样式。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Pseudo-element Styles</title>
    <style>
        #quote::before {
            content: "“";
            font-size: 2em;
            color: red;
        }
        #quote::after {
            content: "”";
            font-size: 2em;
            color: blue;
        }
    </style>
</head>
<body>

<p id="quote">To be or not to be</p>

<script>
    const quote = document.getElementById('quote');
    
    // Get styles for ::before pseudo-element
    const beforeStyles = window.getComputedStyle(quote, '::before');
    console.log('Before content:', beforeStyles.content);
    console.log('Before color:', beforeStyles.color);
    
    // Get styles for ::after pseudo-element
    const afterStyles = window.getComputedStyle(quote, '::after');
    console.log('After content:', afterStyles.content);
    console.log('After color:', afterStyles.color);
</script>

</body>
</html>

这里我们有一个带有 ::before 和 ::after 伪元素的段落。JavaScript 代码使用 getComputedStyle 的第二个参数来访问这些伪元素的样式。

这演示了如何检查应用于伪元素的样式,这些样式无法通过常规 DOM 方法访问。第二个参数指定要定位的伪元素。

比较内联样式和计算后样式

此示例演示了内联样式和计算后样式之间的区别。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Inline vs Computed Styles</title>
    <style>
        #compare {
            font-size: 18px;
            color: green;
        }
    </style>
</head>
<body>

<div id="compare" style="color: red; font-weight: bold;">
    Style Comparison
</div>

<script>
    const div = document.getElementById('compare');
    
    // Inline styles
    console.log('Inline color:', div.style.color);
    console.log('Inline font-size:', div.style.fontSize);
    
    // Computed styles
    const computed = window.getComputedStyle(div);
    console.log('Computed color:', computed.color);
    console.log('Computed font-size:', computed.fontSize);
    console.log('Computed font-weight:', computed.fontWeight);
</script>

</body>
</html>

在此示例中,我们有一个同时具有样式表和内联样式的 div。JavaScript 代码比较了通过 element.stylegetComputedStyle 可访问的内容。

主要区别在于 element.style 仅显示内联样式,而 getComputedStyle 显示所有应用的样式,包括来自样式表的样式。还要注意,element.style 属性是驼峰式(fontSize),而计算后样式是连字符式(font-size)。

检查可见性状态

此示例显示如何使用 getComputedStyle 检查元素是否可见。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Checking Visibility</title>
    <style>
        #hidden {
            display: none;
        }
        #visible {
            visibility: hidden;
        }
    </style>
</head>
<body>

<div id="hidden">This is hidden with display: none</div>
<div id="visible">This is hidden with visibility: hidden</div>
<div id="normal">This is normally visible</div>

<script>
    function checkVisibility(id) {
        const el = document.getElementById(id);
        const style = window.getComputedStyle(el);
        
        console.log(`${id} visibility:`, style.visibility);
        console.log(`${id} display:`, style.display);
        console.log(`${id} is visible:`, 
            style.display !== 'none' && style.visibility !== 'hidden');
    }
    
    checkVisibility('hidden');
    checkVisibility('visible');
    checkVisibility('normal');
</script>

</body>
</html>

这里我们有三个具有不同可见性状态的 div。JavaScript 函数使用 getComputedStyle 来检查它们的 display 和 visibility 属性。

这演示了如何以编程方式确定元素是否可见。请注意,display: nonevisibility: hidden 对可见性的影响不同,并且都需要检查以进行全面评估。

使用计算后样式进行动画

此示例展示了如何在动画中使用 getComputedStyle,通过在动画之前读取当前值。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Animation with Computed Styles</title>
    <style>
        #box {
            width: 100px;
            height: 100px;
            background-color: coral;
            position: relative;
            left: 0;
            transition: left 1s ease;
        }
    </style>
</head>
<body>

<div id="box"></div>
<button onclick="moveBox()">Move Box</button>

<script>
    function moveBox() {
        const box = document.getElementById('box');
        const style = window.getComputedStyle(box);
        
        // Get current left position (returns '0px')
        const currentLeft = parseInt(style.left);
        
        // Move to new position based on current position
        box.style.left = `${currentLeft + 100}px`;
    }
</script>

</body>
</html>

在此示例中,我们有一个框,在单击按钮时会向右移动。JavaScript 使用 getComputedStyle 在计算新位置之前读取当前的 left 位置。

这演示了如何在动画中使用 getComputedStyle 读取当前属性值。请注意,我们使用 parseInt 将 'px' 字符串值转换为数字以进行计算。

来源

MDN getComputedStyle 文档

在本文中,我们展示了如何在 JavaScript 中使用 window.getComputedStyle。此方法对于访问完整的样式信息和创建动态、样式感知型应用程序至关重要。

作者

我叫 Jan Bodnar,是一位充满激情的程序员,拥有丰富的编程经验。我自 2007 年以来一直在撰写编程文章。迄今为止,我已撰写了 1400 多篇文章和 8 本电子书。我在教授编程方面拥有十多年的经验。

列出 所有 JS DOM 教程