按比例微縮圖片的一段小小的JS代碼

來源:互聯網
上載者:User

 11 //智能微縮圖片JS方法
 2 2 //參數:imgID(圖片的標識ID)
 3 3 //參數:maxWidth(圖片的最大寬度,值為0則表示不限制寬度)
 4 4 //參數:maxHeight(圖片的最大高度,值為0則表示不限制高度)
 5 5 function setImgSize(imgID,maxWidth,maxHeight)
 6 6 {
 7 7     var img = document.images[imgID];
 8 8     if(maxWidth < 1)
 9 9     {
1010         if(img.height > maxHeight)
1111         {
1212             img.height = maxHeight;
1313         }
1414         return true;
1515     }
1616     if(maxHeight < 1)
1717     {
1818         if(img.width > maxWidth)
1919         {
2020             img.width = maxWidth;
2121         }
2222         return true;
2323     }
2424     if(img.height > maxHeight || img.width > maxWidth)
2525     {
2626         if((img.height / maxHeight) > (img.width / maxWidth))
2727         {
2828             img.height = maxHeight;
2929         }
3030         else
3131         {
3232             img.width = maxWidth;
3333         }
3434         return true;
3535     }
3636 }

  自己寫的一個非常簡單的圖片微縮JS代碼,當然網上有很多類似的代碼,在此確實是獻醜了。
         主要方法寫在SetImgSize.js裡面
功能實現原理是在圖片載入完畢後(onload事件)用JS實現微縮。
         下面是一個測試用的檔案test.htm


 11 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 2 <html xmlns="http://www.w3.org/1999/xhtml" >
 3 3 <head>
 4 4     <title>測試</title>
 5 5     <script language="javascript" type="text/javascript" src="setImgSize.js"></script>
 6 6 </head>
 7 7 <body>
 8 8     限定了寬度150px
 9 9     <br /><img alt="" id="img1" onload="setImgSize('img1',150,0);" src="http://img.poco.cn/photo/20060602/972374149620060602140117_1.jpg" />
1010     <br />限定了高度150px
1111     <br /><img alt="" id="img2" onload="setImgSize('img2',0,150);" src="http://img.poco.cn/photo/20060602/972374149620060602140117_4.jpg" />
1212     <br />限定了高度150px、寬度150px
1313     <br /><img alt="" id="img3" onload="setImgSize('img3',150,150);" src="http://static.flickr.com/46/147572720_8b25471150_o.jpg" />
1414 </body>
1515 </html>

  就寫到這裡了,呵呵,是不是很簡單啊!
下載SetImgSize.rar

聯繫我們

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