js實現固定顯示地區內自動縮放圖片的方法,js縮放

來源:互聯網
上載者:User

js實現固定顯示地區內自動縮放圖片的方法,js縮放

本文執行個體講述了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="dsds.JPG" 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>

希望本文所述對大家的javascript程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.