效果图:
1、引入jq:
2、添加html部分(引用两张网上图片):
<div class="box">
<div class="list"><img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1551061283&di=1b750c34c5391d7461621053484c6c0b&imgtype=jpg&er=1&src=http%3A%2F%2Fzkres3.myzaker.com%2F201807%2F5b419d167f52e9372f000048_640.jpg" alt=""></div>
<div class="list"><img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1550466565460&di=cc1fd375f156f21a2e0d2e5d6717eabb&imgtype=0&src=http%3A%2F%2Fs9.rr.itc.cn%2Fr%2FwapChange%2F201611_6_11%2Fa99vq51405078985855.jpg" alt=""></div>
</div>
3、添加样式:
.box{width:800px;height:400px;margin: 100px}
.list{display: inline-block;width:160px;height:160px;position: relative;overflow: hidden;border:1px solid #ccc;margin:10px;}
.list img{position: absolute;top:0;left:0;}
4、添加js:
var obgH = 160; // 默认显示图片的高度(与css一致)
var obgW = 160; // 默认显示图片的宽度(与css一致)
var obgClass = $('.list img') // 图片calss
obgImg(obgH,obgW,obgClass)
function obgImg(obgH,obgW,obgClass){
obgClass.each(function(i){ // 遍历
if($(this).width()>$(this).height()){ // 判断宽度是否大于高度
$(this).height(obgH) // 高度等于默认高度
$(this).css("left",-$(this).width()/2+obgW/2+'px'); // left
}else{
$(this).width(obgW) // 宽度等于默认宽度
$(this).css("top",-$(this).height()/2+obgH/2+'px'); // top
}
})
}