(共566篇)
全部分类

获取元素的CSS样式
[ JS基础 ] 

获取元素的CSS样式

通过元素标签上的style属性,只可以获取或者修改元素的内联样式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<style>
    h1 {
        color: red;
    }
</style>

<h1 style="background-color: green;">hello world</h1>
<script>
    var h1 = document.querySelector("h1");
    console.log("使用style属性获取color: ", h1.style.color);
    console.log(
        "使用style属性获取background-color: ",
        h1.style.backgroundColor,
    );
</script>

案例源码

color样式没有定义在元素的style属性内,所以是获取不到的,返回值是一个空字符串。

window.getComputedStyle(element [, pseudoEle])

如果想要获取元素最终的所有样式,可以使用window.getComputedStyle(element [, pseudoEle])方法:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<style>
    h1 {
        color: red;
    }
</style>

<h1 style="background-color: green;">hello world</h1>
<script>
    var h1 = document.querySelector("h1");
    var styles = window.getComputedStyle(h1);
    console.log("color: ", styles.color);
    console.log("background-color: ", styles.backgroundColor);
</script>

案例源码

要注意:该方法中的element必须是个标准的元素节点,如果想要获取一个伪元素的样式,可以利用第二个参数pseudoEle:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<style>
    h1 {
        color: red;
    }
    h1::after {
        content: " china";
        color: green;
    }
</style>

<h1>hello world</h1>
<script>
    var h1 = document.querySelector("h1");

    var currentStyle = window.getComputedStyle(h1, "::after");
    console.log("使用getComputedStyle获取color: ", currentStyle.color);
</script>

案例源码

设置元素样式

通过element.style还可以用来设置元素的样式,这些样式会添加在元素的内联样式中:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<style>
    h1 {
        color: red;
    }
</style>

<h1>hello world</h1>
<script>
    var h1 = document.querySelector("h1");
    console.log("修改前的color: ", window.getComputedStyle(h1).color);

    h1.style.color = "green";
    console.log("修改后的color: ", window.getComputedStyle(h1).color);
</script>

案例源码

注意:使用style设置样式时,样式名需要适应驼峰命名法!