js获取图片原始的宽和高
来源:原创
时间:2016-08-15
作者:脚本小站
分类:JS/JQuery
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> </head> <body onload="realWidth()"> <img src="https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png" id="image" style="width:25px;height:25px;"> <!-- 页面加载完毕才可获取图片的宽和高 --> <script> function realWidth(){ var real_width,real_height; im = document.createElement('img'); im.src = document.getElementById('image').src; alert(im.width+'\n'+im.height); } </script> </body> </html>
Jquery使用示例:
<img width="200" class="images_details" src="http://localhost/Public/images/icon/banner.jpg" alt="" /> // 获取图片原始宽度 var Image = document.createElement('img'); $('.images_details').each(function (i){ Image.src = $(this).prop('src'); RealWidth = Image.width; if(RealWidth > 450){ RealWidth = 450; } $(this).attr('_width',RealWidth); }); // 显示图片原始宽度 $('.images_details').click(function (i){ ShowWidth = $(this).attr('_width') CurrentWidth = $(this).prop('width'); if(ShowWidth == CurrentWidth){ $(this).prop('width',200); }else{ $(this).prop('width',ShowWidth); } });