js控製圖片自動縮放,實現鋪滿盒子,不變形,完全域中

來源:互聯網
上載者:User

標籤:UI   utf-8   src   通過   img   完全   offset   body   cut   

此js一般用於控製圖片鋪滿盒子,但是比例不變,並且絕對局中
原理:判斷圖片的高寬與盒子高寬的大小的關係,然後通過比例來控製圖片的縮放及定位


<!
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>無標題文檔</title><style type="text/css">#img{ width:600px; height:400px; position:relative; overflow:hidden; background:#996699;}</style></head><body><div id="img"><img src="images/test_01.png" onload="resize_img(this,600,400)" /></div></body></html><script type="text/javascript">function resize_img(pic,w,h){//參數 var re_new_size=function(r){ //根據比率重新計算寬度 return {w:pic.width/r,h:pic.height/r}; }; var re_offset=function(n){ //根據新的寬高度返回位移量 return {off_l:(n.w-w)*0.5,off_t:(n.h-h)*0.5}; }; var re_position=function(o,n){ //重新置放圖片 pic.style.cssText="position:absolute;top:"+-o.off_t+"px;left:"+-o.off_l+"px;width:"+n.w+"px;height:"+n.h+"px;"; }; var execute=function(rate){//總執行函數 var new_size=re_new_size(rate), offset_new=re_offset(new_size); re_position(offset_new,new_size); }; //判斷變數 var rate_of_w=pic.width/w, rate_of_h=pic.height/h, rate; if(rate_of_w>=1){ //圖片寬度大於顯示地區寬度 if(rate_of_h>=1){ //且圖片高度大於顯示地區高度 rate=Math.min(rate_of_w,rate_of_h); }else{ //圖片高度小於顯示地區 rate=pic.height/h; } }else{ //圖片寬度小於顯示地區寬度 if(rate_of_h>=1){ //且圖片高度大於顯示地區高度 rate=pic.width/w; }else{ //圖片高度小於顯示地區高度 rate=Math.min(rate_of_w,rate_of_h); } } execute(rate); //執行入口 }</script>

 

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.