JavaScript-怎么解决javascript取图片尺寸第一次是0,0
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JavaScript获取图片大小</title>
</head>
<script>
var imgSize=[0,0];
var imgSizeReturn=function(tempObj){
imgSize[0]=tempObj.height;
imgSize[1]=tempObj.width;
alert(imgSize);
};
var setImgSrc=function(){
document.getElementById('hiddenImg').src="136300066089774700_a_4.jpg";
imgSizeReturn(document.getElementById('hiddenImg'));
};
</script>
<body>
<img id="hiddenImg" style="visibility:hidden; position:absolute; z-index:-10; top:0; left:0;"/>
<input type="button" onclick="setImgSrc()" value="获取" />
</body>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

问题出在setImgSrc()函数,因为你设置图片的src之后立即调用imgSizeReturn(),这时候图片其实还没有加载完成,所以取到的width和height都是0。
解决办法:等图片onload以后再调用imgSizeReturn()函数。setImgSrc()可以改成下面这样:
var setImgSrc=function(){
document.getElementById('hiddenImg').onload = function(){
imgSizeReturn(document.getElementById('hiddenImg'));
}
document.getElementById('hiddenImg').src="136300066089774700_a_4.jpg";
};