這篇文章主要介紹了js實現固定顯示區域內自動縮放圖片的方法,實例分析了javascript操作頁面元素及屬性的相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了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程序設計有所幫助。
新聞熱點
疑難解答
圖片精選