DOM图片显示优化处理

在列表显示中,常见就是文字+图片形式的布局。小程序中的 <image> 组件有几种固定的图片显示模式,来适应不同需求下的图片显示需求,在web app开发中我们也可以根据不同图片的大小尺寸进行定位处理,让图片使用相对显示居中。

首先dom必须符合以下基本结构:

<div class="thumb_box">
    <img />
</div>

同时 .thumb_box 必须要添加的css属性:

.thumb_box {
  position: relative; /* absolute也可以 */
  overflow: hidden;    
}

加载图片时调用下述方法即可处理调整

 1 $.fn.imgCenter = function(a, b) {
 2     return this.each(function() {
 3         var e = $(this),
 4             p = e.parent(),
 5             w = a || e.width(),
 6             h = b || e.height(),
 7             W = p.outerWidth(),
 8             H = p.outerHeight(),
 9             t = W * h / w,
10             l = H * w / h;
11         if (/relative|absolute/i.test(p.css('position')) && p.css('overflow') == 'hidden' && W > 0 && H > 0) {
12             e.css(function() {
13                 return (W > H && t <= H) || (W <= H && l >= W) ? {
14                     'position': 'absolute',
15                     'top': '0',
16                     'left': -(l - W) / 2,
17                     'width': 'auto',
18                     'height': '100%'
19                 } : {
20                     'position': 'absolute',
21                     'top': -(t - H) / 2,
22                     'left': '0',
23                     'width': '100%',
24                     'height': 'auto'
25                 };
26             }()).removeAttr('width height');
27         }
28     });
29 };

另外对于未知图片宽高且需让图片显示于元素中间位置的情况, 可利用inline-block的vertical-align属性搭配伪类(::after)来实现居中显示

.center_img_box {
  width: 100%;
  height: 500px;
  font-size: 0;
  *font-size: 200px;
  text-align: center;
}
.center_img_box img {
  width: 50%;
  height: auto;
    vertical-align: middle;
}
.center_img_box:after {
  display: inline-block;
  width: 0;
  height: 100%;
  content: "center";
  vertical-align: middle;
  overflow: hidden;
}
原文地址:https://www.cnblogs.com/matthewkuo24/p/14060056.html