使用方法:
1.定义ResizeImg(obj)方法
function ResizeImg(obj) {
var boxHeight = $(".box").height();
var boxWidth = $(".box").width();
var imgHeight = $(obj).height();
var imgWidth = $(obj).width();
$(obj).css("position", "relative");
if (imgHeight * boxWidth >= imgWidth * boxHeight) {
//调整后,高度超出的情况
var afterImgHeight = boxWidth * imgHeight / imgWidth;
$(obj).css("width", boxWidth + "px").css("height", afterImgHeight + "px");
var offsetTop = (afterImgHeight / 2) - (boxHeight / 2);
$(obj).css("top", "-" + offsetTop + "px"); // -20px
}
else {
//调整后,宽度超出的情况
var afterImgWidth = boxHeight * imgWidth / imgHeight;
$(obj).css("height", boxHeight + "px").css("width", afterImgWidth + "px");
var offsetLeft = (afterImgWidth / 2) - (boxWidth / 2);
$(obj).css("left", "-" + offsetLeft + "px"); // -20px
}
console.log("resize ok.");
}
2.在img标绑定onload事件处理方法为ResizeImg.
<img src="xxx.jpg" onload="ResizeImg(this)"/>
3.注意:
不设置图片的宽,高;
需设置图片定位属性,position: relative;
效果如下图: