Javascript图像宽度和高度未定义值
Javascript image width and height undefined values
我试图从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/
相关文章:
- 为什么“;未定义的“;在JavaScript中结束循环
- 要求未定义JS回调参数
- 如何检查管道中未定义的项目
- TypeError:无法读取属性'推'未定义的JavaScript
- $window.ga在AngularJS事件中未定义
- 未捕获的TypeError无法读取未定义的属性socialsharing
- 为什么grunt contrib connect的中间件选项的第三个参数是未定义的
- 无法获取属性'selectedIndex'的未定义引用或null引用
- 如何消除代码中的未定义和其他问题
- 未捕获的ReferenceError:$未定义
- this.router在AngularJS 2中未定义
- 未捕获的类型错误:无法读取属性'删除'的未定义
- 节点fs.stat名称未定义
- 尝试在PHP中回显输入文本时出现未定义的索引错误
- Jquery未定义函数正在停止其他操作
- Javascript图像宽度和高度未定义值
- 无法设置属性'高度'的未定义
- 具有初始未定义高度的jQueryui动画
- 是否可以使用jQuery来查找高度未定义的文本跨度的高度
- 宽度和高度未定义- Javascript/jQuery