【Javascript】原生js图片自适应尺寸居中函数处理

 1 /*
 2  |  autoSerializePicture.js 自适应格式化图片
 3  |  auther : baichaohua/2017-09-21
 4  +------------------------------------------------ */
 5 
 6 /*  JSON 示例
 7 [
 8     { 
 9         "imgSrc":"logo.png",   //路径
10         "imgText":"示例图片1", //文本
11         "width":"185",         //原始宽
12         "height":"185"         //原始高
13     },
14     {
15         "imgSrc":"1.jpg",
16         "imgText":"示例图片2",
17         "width":"1024",
18         "height":"640"
19     }
20 ]
21 */
22 // 用法示例:addPictureAutoSize(json数据, 父级:document.getElementById('xxx')元素-默认body, );
23 
24 var autoSerializePicture = function (json, parent, callback) {
25 
26     var obj      = JSON.parse(json);
27     var totalDiv = document.createElement('div');
28     totalDiv.id  = 'autoSerializePictureBox';
29 
30     for (var i = 0; i < obj.length; i++) {
31         var box      = document.createElement('div');
32         var imgDIv   = document.createElement('imgDIv');
33         var p        = document.createElement('p');
34         var pv       = document.createElement('p');
35         var textNode = document.createTextNode(obj[i].imgText);
36 
37         var width  = obj[i].width * 300 / obj[i].height;
38         var height = obj[i].height * 300 / obj[i].width;
39 
40         var img  = new Image();
41         img.src  = obj[i].imgSrc;
42 
43         if (obj[i].width / obj[i].height >= 1) 
44             img.style.cssText = ' 300px; height: auto;position: absolute;left: 50%;margin-left: -150px;top: 50%;margin-top: -' + height / 2 + 'px';
45         else
46             img.style.cssText = ' auto; height: 300px;position: absolute;left: 50%;margin-left: -' + width / 2 + 'px;top: 50%;margin-top: -150px';
47 
48         imgDIv.style.cssText = '300px;height: 300px;position:relative;float: left; border: 1px solid #eee;padding: 8px;margin-top: 0px;';
49         box.style.cssText    = 'overflow: hidden;300px;height: 350px;position:relative;float: left;padding: 8px;margin-top: 0px;';
50         p.style.cssText      = 'text-align: center;margin-top: 324px;';
51         pv.style.cssText     = 'height: 40px;';
52 
53         imgDIv.appendChild(img);
54         p.appendChild(textNode);
55         box.appendChild(imgDIv);
56         box.appendChild(p);
57         box.appendChild(pv);
58         totalDiv.appendChild(box);
59     }
60     if(parent)
61         parent.appendChild(totalDiv);
62     else
63         document.getElementsByTagName('body')[0].appendChild(totalDiv);
64 
65     if (callback) callback(json);
66 
67     return {
68         //...
69     }
70 }

今天同事遇到一个问题,就是有很多图片,需要生成列表,但是图片大小需要自适应且居中,就写了一个方法。

直接上代码了,自适应格式化图片,图片效果:

原文地址:https://www.cnblogs.com/bc8web/p/7570837.html