JQ 获取图片真实宽高
程序员文章站
2022-03-11 23:05:37
...
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <title>JQ 获取图片真实宽高</title> <script>window.jQuery || document.write(unescape("%3Cscript src='http://libs.baidu.com/jquery/1.10.1/jquery.min.js' type='text/javascript'%3E%3C/script%3E")); </script> <style type="text/css"> #image{ width: 200px; height: 150px;} </style> </head> <body> <img src="aaa.jpg" width="400" height="300" id="image"> <script type="text/javascript"> $(function(){ var imgSrc = $("#image").attr("src"); getImageWidth(imgSrc,function(w,h){ console.log({width:w,height:h}); }); }); function getImageWidth(url,callback){ var img = new Image(); img.src = url; // 如果图片被缓存,则直接返回缓存数据 if(img.complete){ callback(img.width, img.height); }else{ // 完全加载完毕的事件 img.onload = function(){ callback(img.width, img.height); } } } </script> </body> </html>
效果图: