標籤:style set etl 事件處理 效果 ons 垂直置中 div 高度
使用方法:
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"); // -20px12 }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"); // -20px19 }20 console.log("resize ok.");21 }
2.在img標綁定onload事件處理方法為ResizeImg.
<img src="xxx.jpg" onload="ResizeImg(this)"/>
3.注意:
不設定圖片的寬,高;
需設定圖片定位屬性,position: relative;
效果如:
js指令碼控製圖片水平與垂直置中