javascript-通过getComputedStyle()计算元素的所有样式

本文介绍如何使用getComputedStyle()方法获取HTML元素的实际样式,包括所有默认样式,并提供了一个兼容IE8的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

javascript-计算元素的所有样式

在日常开发中,如果你需要读取html元素的style样式或class样式的属性值时,就可以使用DOM2级样式中新增的方法-getComputedStyle()

getComputedStyle()

getComputedStyle()方法是window对象的方法,可以通过window.getComputedStyle(),或者document.defaultView.getComputedStyle()方法调用。而document.defaultView的返回值就是window。
接收2个参数:

  • 需要计算样式的元素,必须
  • 伪元素字符串(’:after’),非必须
    示例如下:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>计算样式</title>
    <style>
        #content{
            width: 300px;
            height: 200px;
            background-color: darkgrey;
        }
    </style>
</head>
<body>
    <div id="content" style="background-color: darkmagenta;">
        内容区域
    </div>
    <script>
        var content = document.querySelector('#content')
        var computedStyle = document.defaultView.getComputedStyle(content, null)
        var html = ''
        function getComputedStyleValue(computedStyle, property){
            return property + ': ' + computedStyle[property] + ';'
        }
        html = '<span>'+getComputedStyleValue(computedStyle, 'background-color')+'</span><br/>'+
        '<span>'+getComputedStyleValue(computedStyle, 'width')+'</span><br/>' +
        '<span>'+getComputedStyleValue(computedStyle, 'height')+'</span><br/>'
        content.innerHTML = html
    </script>
</body>
</html>

这里写图片描述
这里写图片描述
如上图所示:
浏览器通过getComputedStyle()方法读取样式,这些样式是可读的,也包括所有的默认样式。background-color被替换了,且浏览器将颜色转成rgb格式,经测试,IE10/11,Chrome等5大主流浏览器都支持该方法。

兼容IE8

var content = document.querySelector('#content')
        var computedStyle = getConstantStyle(content, null)
        var html = ''
        function getComputedStyleValue(computedStyle, property){
            return property + ': ' + computedStyle[property] + ';'
        }
        // 获取计算样式
        function getConstantStyle(el, pelStr){
            var w = document.defaultView
            if (w && w.getComputedStyle) {
                return document.defaultView.getComputedStyle(el, pelStr)
            } else {
                return el.currentStyle
            }
        }
        html = '<span>'+getComputedStyleValue(computedStyle, 'background-color')+'</span><br/>'+
        '<span>'+getComputedStyleValue(computedStyle, 'width')+'</span><br/>' +
        '<span>'+getComputedStyleValue(computedStyle, 'height')+'</span><br/>'
        content.innerHTML = html

IE8会显示该颜色的原始名称,即:darkmagenta

小结

  • 通过getComputedStyle()可以获取元素的所有样式属性
  • 计算样式属性都是只读的,不能设置
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值