Javascript图像宽度和高度未定义值

Javascript image width and height undefined values

本文关键字:高度 未定义 图像 Javascript      更新时间:2023-09-26

我试图从previewFrame中获取宽度和高度,并将两者的值都设置为100%,但当我试图提醒它时,总是会得到未定义的值。这是我的html文件:

<html>
<head>
    <link rel="stylesheet" href="frame.css">
</head>
<body>
<div id="previewWrapper">
    <div id="previewFrame">
        <img id="previewImage" src="http://i.forbesimg.com/media/lists/companies/google_416x416.jpg">                    </img>
    </div>
</div>
<script src="frame.js"></script>
</body>

这是我的css:

html, body{
    margin:0;
    background:#ccc;
}
#previewWrapper{
    margin:44px 0px;
    width:100%;
    height:calc(100% - 88px);
}
#previewFrame{
    width:100%;
    height:100%;
    margin-top:44px;
    background:#000;
}
#previewFrame img{
    max-width:100%;
    max-height:100%;
}

这是我的js:

    function imageInfo() {
    var pFrame = document.getElementById("previewFrame");
    pFrame.setAttribute('style', "width: 100%; height: calc(100% - 88px);");
    var frameWidth = pFrame.width;
    var frameHeigh = pFrame.height;
    var pImage = document.getElementById("previewImage");
    var imageWidth = pImage.width;
    var imageHeigh = pImage.height;
    alert('Frame size is '+frameWidth+'px x '+frameHeigh+'px');
}
window.onload = imageInfo;

首先,setAttribute是一个方法,而不是属性为style的对象。所以应该是

pFrame.setAttribute('style', "width: 100%; height: calc(100% - 88px);");

第二个问题是,为了读取浏览器计算的CSS属性,您需要使用getComputedStyle方法:

var pFrameStyle = window.getComputedStyle(pFrame, null);
var frameWidth = pFrameStyle.width;
var frameHeigh = pFrameStyle.height;

演示:http://jsfiddle.net/yxz4201q/2/