FairyTalesss 2023-02-21 13:13 采纳率: 78.6%
浏览 32
已结题

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

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

<!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 = one.style['width'];
    var box_height = one.style['height'];
    console.log(box_width);
    console.log(box_height);
</script>
</html>

  • 写回答

3条回答 默认 最新

  • Web Security Loop 2023-02-21 13:43
    关注

    你尝试使用 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 属性的值。这样,你就可以在控制台中正确地显示这些属性的值。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 3月3日
  • 已采纳回答 2月23日
  • 创建了问题 2月21日

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)