JavaScript读取Css属性并打印在控制台

我在使用JavaScript读取页面元素css属性时,发现控制台中打印的属性值为空。如何将正确的属性值呈现在控制台中?

html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        .my_box{
            width: 250px;
            height: 250px;
            background-color: cornflowerblue;
        }
    style>
    <title>Documenttitle>
head>
<body>
    <div class="my_box">div>
body>
<script>
    var one = document.querySelector(".my_box");
    var box_width = one.style['width'];
    var box_height = one.style['height'];
    console.log(box_width);
    console.log(box_height);
script>
html>

你尝试使用 one.style 属性读取 width 和 height 的值。但是,style 属性只能读取已经直接在元素的 style 属性中定义的样式。在你的示例中,你的 width 和 height 属性是通过 CSS 类 .my_box 中的样式规则来定义的。要读取从样式表定义的值,你需要使用 window.getComputedStyle() 方法。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        .my_box{
            width: 250px;
            height: 250px;
            background-color: cornflowerblue;
        }
    </style>
    <title>Document</title>
</head>
<body>
    <div class="my_box"></div>
</body>
<script>
    var one = document.querySelector(".my_box");
    var box_width = window.getComputedStyle(one).getPropertyValue('width');
    var box_height = window.getComputedStyle(one).getPropertyValue('height');
    console.log(box_width);
    console.log(box_height);
</script>
</html>


使用 window.getComputedStyle() 方法获取元素的计算样式,然后使用 getPropertyValue() 方法读取 width 和 height 属性的值。这样,你就可以在控制台中正确地显示这些属性的值。

可以使用window.getComputedStyle(one,null)['width']来获取属性(但是ie6~8不支持这个属性哦),取出来的结果应该是250px,带单位的,如果要不带单位的话用正则去掉。
代码如下:

var val = null,reg = null;    
val = window.getComputedStyle(one,null)['width'];  //ie6~8不支持此属性 
reg = /^(-?\d+(\.\d)?)(px|pt|em|rem)?$/i;  
console.log( reg.test(val)?parseFloat(val):val );