Javascript 为什么IE11返回错误的img.width和img.height(28x30像素)用于静态加载图像?
我想在加载图像时检查图像宽度:Javascript 为什么IE11返回错误的img.width和img.height(28x30像素)用于静态加载图像?,javascript,internet-explorer,internet-explorer-11,Javascript,Internet Explorer,Internet Explorer 11,我想在加载图像时检查图像宽度: <img src="http://upload.wikimedia.org/wikipedia/commons/3/34/Regensburg_Uferpanorama_08_2006.jpg" id="img" alt="" /> <pre id="pre "></pre> <script> var i = 0; var img = document.getElementById("img"); var pre =
<img src="http://upload.wikimedia.org/wikipedia/commons/3/34/Regensburg_Uferpanorama_08_2006.jpg" id="img" alt="" />
<pre id="pre "></pre>
<script>
var i = 0;
var img = document.getElementById("img");
var pre = document.getElementById("pre");
function checkWidth() {
i++;
pre.innerHTML += "width:" + img.width + ";height:" + img.height + "\n";
if (i < 20) {
setTimeout(function() {
checkWidth();
}, 100);
}
}
checkWidth();
</script>
var i=0;
var img=document.getElementById(“img”);
var pre=document.getElementById(“pre”);
函数checkWidth(){
i++;
pre.innerHTML+=“宽度:”+img.width+“高度:”+img.height+“\n”;
如果(i<20){
setTimeout(函数(){
检查宽度();
}, 100);
}
}
检查宽度();
现在我已经测试了几个浏览器,在加载图像头(不是完整的图像)之前,所有浏览器都返回0x0。然后返回正确的尺寸(例如1920x1080)
但Internet Explorer 11(我只能测试这个浏览器版本)在加载标题之前,每幅图像返回28x30像素(与纵横比无关)
为什么IE11返回这个维度?这是所有IE版本中的常见行为吗?@mouser的想法是正确的。它是断开图像的占位符:
我的解决方案是使用img.naturalWidth()而不是这里描述的img.width:
这将返回0x0,直到图像头被加载。它是图像预加载图标的大小。我猜这是错误图像图标的尺寸。运行该代码
img.onload=function(){/*in here*/}
。当然,您必须设置src
,这看起来很像。@PHPglue在加载整个图像时会起作用,但在IE中已经起作用了。OP的问题是,在接收到图像的标题(元数据)后,它的大小与Chrome中的不一样。它将等待图像完全加载以执行此操作。@Mouser Yes您是正确的。我会更新我的问题。