js腳本控制圖片水平與垂直居中
阿新 • • 發佈:2017-08-22
處理方法 cti 超出 1-1 es2017 ole div http con
使用方法:
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(); 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;
效果如下圖:
js腳本控制圖片水平與垂直居中