js指令碼控製圖片水平與垂直置中

來源:互聯網
上載者:User

標籤: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指令碼控製圖片水平與垂直置中

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.