前言
最近再做個(gè)H5移動(dòng)端社交類型項(xiàng)目的時(shí)候,里面有一塊 類似朋友圈、qq空間展示的模塊,開發(fā)的時(shí)候發(fā)現(xiàn)了一個(gè)問題,就是展示用戶上傳的圖片,因?yàn)橛脩羯蟼鞯膱D片 可能是相機(jī)拍的,可能是截圖、可能是網(wǎng)上找的,但是這樣會(huì)存在一個(gè)圖片不規(guī)則的問題,因?yàn)槲覀兪切枰故究s略圖的,如果圖片的尺寸不滿足我們的要求,我們既不能 設(shè)置高寬為100%,因?yàn)檫@樣可能會(huì)存在圖片拉伸、擠壓的情況;如下是我的解決方法。
不規(guī)則素材

效果圖

image.png
主要代碼
主要html
<!-- _1_2 圖片顯示數(shù)量為1-2張的樣式 _3_9 圖片顯示數(shù)量為3-9張的樣式 -->
<div class="img_body _3_9">
<div class="img_ctx">
<img src="imgs/test2.png" alt="">
</div>
<div class="img_ctx">
<img src="imgs/test_phone.png" alt="">
</div>
<div class="img_ctx">
<img src="imgs/test_phone.png" alt="">
</div>
<div class="img_ctx">
<img src="imgs/test2.png" alt="">
</div>
<div class="img_ctx">
<img src="imgs/test_phone.png" alt="">
</div>
<div class="img_ctx">
<img src="imgs/test_phone.png" alt="">
</div>
<div class="clear"></div>
</div>
主要css
.img_body .img_ctx {
display: block;
float: left;
border-radius: 5px;
box-shadow: 0px 2px 5px 0px rgba(6, 190, 188, 0.2);
background-position: center center;
}
.img_body .img_ctx img{display: none;}
.img_body._1_2 .img_ctx {
width: 49%;
margin-right: 2%;
margin-top: 2%;
}
.img_body._1_2 .img_ctx:nth-child(2) {
margin-right: 0;
}
.img_body._3_9 .img_ctx {
width: 32.5%;
margin-right: 1.25%;
margin-top: 1.25%;
}
.img_body._3_9 .img_ctx:nth-child(3){margin-right: 0;}
.img_body._3_9 .img_ctx:nth-child(6){margin-right: 0;}
.img_body._3_9 .img_ctx:nth-child(9){margin-right: 0;}
主要js
$(function(){
//獲取所有沒處理的 img
$.each($('.img_ctx img'),function(i,v){
//獲取包裹img的div
var $img_parent= $(v).parent();
//設(shè)置這個(gè)div的高度
$img_parent.height($img_parent.width());
//設(shè)置背景圖為 當(dāng)前的img
$img_parent.css({backgroundImage:'url('+$(v).attr('src')+')'})
//如果圖片長寬一樣 則設(shè)置寬度百分之百
if($(v).width()==$(v).height()){
$img_parent.css({backgroundSize:'100% 100%'})
}
//如果寬大于高 高度100%
if($(v).width()>$(v).height()){
//縮略百分比后的寬度
var _width=$(v).width()*($img_parent.width()/$(v).height());
$img_parent.css({backgroundSize: _width +'px 100%'})
}else{//寬度 100%
$img_parent.css({backgroundSize:'100%'})
}
//處理完圖片后 把 img刪掉,代表這個(gè)img已經(jīng)處理過了
$(v).remove();
})
})