小白小白从不日白 2021-10-29 13:32 采纳率: 66.7%
浏览 36

getComputedStyle()获取img属性问题

在通过getComputedStyle()方法获取ul li下面的img的宽度

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title></title>
    <!-- <link rel="stylesheet" href="fonts/iconfont.css"> -->
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        .box {
            width: 670px;
            height: 300px;
            border: 1px solid #000;
            margin: 100px auto;
            position: relative;
        }
        
        .box>ul {
            list-style: none;
            display: flex;
            /* overflow: hidden; */
        }
        
        .box>p {
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 100%;
            display: flex;
            justify-content: space-between;
        }
        
        .box>p>span {
            width: 30px;
            height: 60px;
            background: rgba(0, 0, 0, .5);
            color: #fff;
            font-size: 40px;
            line-height: 60px;
        }
    </style>
</head>

<body>
    <div class="box">
        <ul>
            <li>
                <img src="images/ad1.jpg" alt="">
            </li>
            <li>
                <img src="images/ad2.jpg" alt="">
            </li>
            <li>
                <img src="images/ad3.jpg" alt="">
            </li>
        </ul>
        <p>
            <span class="left">&lt;</span>
            <span class="right">&gt;</span>
        </p>
    </div>
    <script>
        //1.拿到需要操作的元素
        const oLeft = document.querySelector(".left");
        const oRight = document.querySelector(".right");
        const oUl = document.querySelector("ul");
        const oItems = document.querySelectorAll("ul>li");
        const imgWidth = parseFloat(getComputedStyle(oItems[0]).width);
        console.log(imgWidth);//0

        //2.
    </script>
</body>

</html>

对于最终的结果不理解为什么为 0
补充:在IE11下能得到预期的结果 670,但是在谷歌浏览器下却是0

  • 写回答

2条回答 默认 最新

  • chenrynet 2021-10-29 14:47
    关注

    图片不应该在onload里面拿吗 图片还没加载 没宽度

    评论

报告相同问题?

问题事件

  • 修改了问题 10月29日
  • 创建了问题 10月29日