js脚本控制图片水平与垂直居中
使用方法:
1.定义ResizeImg(obj)方法
1 function ResizeImg(obj) { 2 var boxHeight = $(".box").height(); 3 var boxWidth = $(".box").width(); 4 var imgHeight = $(obj).height(); 5 var imgWidth = $(obj).width();
$(obj).css("position", "relative"); 6 if (imgHeight * boxWidth >= imgWidth * boxHeight) { 7 //调整后,高度超出的情况 8 var afterImgHeight = boxWidth * imgHeight / imgWidth; 9 $(obj).css("width", boxWidth + "px").css("height", afterImgHeight + "px"); 10 var offsetTop = (afterImgHeight / 2) - (boxHeight / 2); 11 $(obj).css("top", "-" + offsetTop + "px"); // -20px 12 } 13 else { 14 //调整后,宽度超出的情况 15 var afterImgWidth = boxHeight * imgWidth / imgHeight; 16 $(obj).css("height", boxHeight + "px").css("width", afterImgWidth + "px"); 17 var offsetLeft = (afterImgWidth / 2) - (boxWidth / 2); 18 $(obj).css("left", "-" + offsetLeft + "px"); // -20px 19 } 20 console.log("resize ok."); 21 }
2.在img标绑定onload事件处理方法为ResizeImg.
<img src="xxx.jpg" onload="ResizeImg(this)"/>
3.注意:
不设置图片的宽,高;
需设置图片定位属性,position: relative;
效果如下图: