不规格图片等比例展示---上下/左右留白

最终效果如下:
不规格图片等比例展示---上下/左右留白_第1张图片
思路:
固定img标签的宽、高,img标签自身内的图像等比例缩放,img标签margin实现留白;使用js计算图片宽、高及margin的值,动态生成样式数据给标签使用。

代码是typescript实现的,js写法应该也差不多的,仅供大家参考:

html代码

<span style="vertical-align:top; width: 370px; display: inline-block;">
   <span
       v-for="(imageMessage,index) in imageMessages"
       style="width: 112px;height: 112px;display: inline-block;
       border: 1px #D7D9D9 solid;margin: 0px 10px 10px 0;"
       :key="index + '-imageMessage'"
       @click="hitClick(imageMessage.id)"
      >
           <img
               ref="imgRef"
               class="img"
               :src="messageGetUrl(imageMessage)"
               :style="getStyle(imageMessage)"
           />
   </span>
</span>

typescript代码

getStyle(message:Message){
     const sideLength = 110;
     const obj = JSON.parse(message.msg);
     console.log('图片信息解析 0 ', obj.h, obj.w, obj);
     if (obj.h==obj.w){
         console.log('图片信息解析 1 ', obj.h, obj.w,sideLength,sideLength, {"width": `${sideLength}px`,"height": `${sideLength}px`});
         return {"width": `${sideLength}px`,"height": `${sideLength}px`};
     }else if (obj.h>obj.w){
         let w = Number(parseInt((obj.w*sideLength/obj.h).toString()));
         let margin = Number(parseInt(((sideLength - w)/2).toString()));
         console.log('图片信息解析 1 ', obj.h, obj.w,sideLength,w, {"width": `${w}px`,"height": `${sideLength}px`,"margin": `0 ${margin}px 0 ${margin}px`});
         return {"width": `${w}px`,"height": `${sideLength}px`,"margin": `0 ${margin}px 0 ${margin}px`};
     }else {
         let h = Number(parseInt((obj.h*sideLength/obj.w).toString()));
         let margin= Number(parseInt(((sideLength - h)/2).toString()));
         console.log('图片信息解析 1 ', obj.h, obj.w,h,sideLength, {"width": `${sideLength}px`,"height": `${h}px`,"margin": `${margin}px 0 ${margin}px 0`});
         return {"width": `${sideLength}px`,"height": `${h}px`,"margin": `${margin}px 0 ${margin}px 0`};
     }
 }

补充:

最新方法:

img{  
    width: auto;  
    height: auto;  
    max-width: 100%;  
    max-height: 100%;     
}  

这样可以实现等比例缩放
然后参照我原来的js,只计算padding就可以了

你可能感兴趣的:(前端)