让页面上图片不变形

很多列表图片的原图超过指定大小,然而图片本身高宽比例不是固定的,因此在设置此类情况时最好的处理方式是使用js来固定图片大小并保证图片居中,且让图片不变形。

js代码:

   1:  /******************************************************************/
   2:  /******将图片居中,在图片外面嵌套一个div不设置任何样式*************/
   3:  /******参数:图片最大宽度,图片最大高度,******/
   4:  /******调用方法:$('.class').centerImage({MaxWidth:190,MaxHeight:135})*************/
   5:  /******************************************************************/
   6:  (function ($) {
   7:      $.fn.centerImage = function (options) {
   8:          var opts = $.extend({}, {
   9:              MaxWidth: 190, MaxHeight: 135
  10:          }, options);
  11:          var img = new Image(); //创建一个Image对象,实现图片的预下载
  12:          img.src = $(this).attr('src');
  13:          var oldImg = $(this);
  14:          if (img.complete) { // 如果图片已经存在于浏览器缓存,直接调用回调函数
  15:              SetImageCenter(img, oldImg, opts);
  16:              return; // 直接返回,不用再处理onload事件
  17:          } else {
  18:              img.onload = function () { //图片下载完毕时异步调用callback函数。
  19:                  SetImageCenter(img, oldImg, opts); //将回调函数的this替换为Image对象
  20:              };
  21:          }
  22:      }
  23:      function SetImageCenter(img, imgold, opts) {
  24:          var iwidth = opts.MaxWidth;
  25:          var iheight = opts.MaxHeight;
  26:          //设置图片的高宽
  27:          if (img.width > 0 && img.height > 0) {
  28:              if (img.width / img.height >= iwidth / iheight) {
  29:                  if (img.width > iwidth) {
  30:                      imgold.css({  iwidth, height: (img.height * iwidth) / img.width });
  31:                  } else {
  32:                      imgold.css({  img.width, height: img.height });
  33:                  }
  34:              } else {
  35:                  if (img.height > iheight) {
  36:                      imgold.css({  (img.width * iheight) / img.height, height: iheight });
  37:                  } else {
  38:                      imgold.css({  img.width, height: img.height });
  39:                  }
  40:              }
  41:          }
  42:          //设置图片外层div的margin-top和margin-left
  43:          var div = imgold.parent(); //获取包含本图片的div
  44:          if (imgold.height() < iheight) {
  45:              var top = (iheight - imgold.height()) / 2;
  46:              div.css('margin-top', top + 'px');
  47:          }
  48:          if (imgold.width() < iwidth) {
  49:              var left = (iwidth - imgold.width()) / 2;
  50:              div.css('margin-left', left + 'px');
  51:          }
  52:      }
  53:  })(jQuery);
  54:   

需要使用jq1.7.2以上。

调用方式:

   1:   $("img[flag=img]").each(function (){
   2:                  $(this).centerImage({ MaxWidth: 190, MaxHeight: 135 });
   3:              });
如果使用:$("img[flag=img]").centerImage({ MaxWidth: 190, MaxHeight: 135 });会导致页面上的图片变形,但图片整体大小会以用户设置的大小为准。
原文地址:https://www.cnblogs.com/maomao999/p/3708506.html