<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>ResizeImage</title> <link rel="stylesheet" href="http://cdn.bootcss.com/meyer-reset/2.0/reset.min.css"> <style type="text/css"> .pics li { float: left; margin-left: 10px; } .pics li a { display: block; width: 100px; height: 100px; overflow: hidden; background: #f1f1f1; position: relative; } .pics li img{display: block;} </style> </head> <body> <ul class="pics"> <li> <a href="javascript:void(0)" title="图片2" class="resizeimg"> <img class="lazy" src="http://img2.xcabc.com/201708/18/20170818095705122440.jpg" /> </a> </li> <li> <a href="javascript:void(0)" title="图片2" class="resizeimg"> <img class="lazy" src="http://img2.xcabc.com/201708/18/20170818100602895954.jpg" /> </a> </li> <li> <a href="javascript:void(0)" title="图片2" class="resizeimg"> <img class="lazy" src="http://img2.xcabc.com/201708/09/20170809110939985639.jpg" /> </a> </li> <li> <a href="javascript:void(0)" title="图片1" class="resizeimg"> <img class="lazy" src="http://img2.xcabc.com/201710/11/20171011051711413154.png" /> </a> </li> </ul> </body> <script src="http://cdn.bootcss.com/jquery/1.11.0/jquery.min.js"></script> <script type="text/javascript"> $(function(){ function ResizeImage(wrap){ var img = new Image(); img.onload=function(){ var wrapRatio; var imgRatio; var wrap_w= $(wrap).width(); var wrap_h= $(wrap).height(); var img_w= img.width; var img_h= img.height; wrapRatio = wrap_w/wrap_h; imgRatio = img_w/img_h; console.log(imgRatio); if(wrapRatio==imgRatio){ $(wrap).find('img').width('100%'); }else if(wrapRatio<imgRatio){ $(wrap).find('img').css({'position':'absolute','width':'100%','top':'50%','transform':'translateY(-50%)'}); }else if(wrapRatio>imgRatio){ $(wrap).find('img').css({'position':'absolute','height':'100%','margin':'0 auto','left':'50%','transform':'translateX(-50%)'}); } } img.src = $(wrap).find('img').attr('src'); console.log(img.src); } var wraps=$('.resizeimg'); for (var i=0;i<wraps.length;i++) { var item=wraps.eq(i); ResizeImage(item); } }); </script> </html> 提示:你可以先修改部分代码再运行。 转载请注明:有爱前端 » 图片缩放 喜欢 (0)or分享 (0)