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日

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度