即使图片在隐藏状态也可以获取

DEMO:http://ouyo.info/lab/getImageSize/index.html

代码如下:

<!doctype html>

<html> <head> <meta charset="utf-8"> <title>兼容浏览器的获取图片尺寸</title> <style type="text/css"> #img{ display:none; } </style> </head> <body>

兼容浏览器的获取图片尺寸

图片目前是隐藏状态 display:none;

</body> <script type="text/javascript"> var getImageSize=function(cfg){ if(cfg.img.complete||cfg.img.width&&cfg.img.height&&cfg.img.width<cfg.img.maxWidth){ cfg.oncomplete.call({ "img":cfg.img, "width":cfg.img.width, "height":cfg.img.height },null); return; } var img=document.createElement("img"),callback=cfg.oncomplete; img.src=cfg.img.src; img.style.cssText="position:absolute;visibility:hidden;left:-9999px;top:-9999px"; document.body.appendChild(img); img.onload=img.onerror=img.onreadystatechange=function(){ if(img&&img.readyState&&img.readyState!='loaded'&&img.readyState!='complete'){ return false; } img.onload=img.onerror=img.onreadystatechange=null; callback.call({ "img":cfg.img, "width":img.width, "height":img.height },null); img.parentElement.removeChild(img); img=null; } } var img=document.getElementById("img"); getImageSize({ "img":img, "maxWidth":1000, "oncomplete":function(){ alert(this.width+":"+this.height); } }) </script> </html>