仿百度图片自适应

其实这个实例来自http://www.w3cfuns.com/blog-5400161-5394900.html

我只是稍微改了一下,觉得这个功能还是很实用的。

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5 <title>无标题文档</title>
 6 <style type="text/css">
 7 .box { width:200px; height:200px; padding:10px; float:left; text-align:center; border:#ddd solid 1px; margin-right:20px; }
 8 </style>
 9 </head>
10 <body>
11     <div id="imgList">
12         <div class="box"><img src="images/oldman.jpg" /></div>
13         <div class="box"><img src="images/lovers.jpg" /></div>
14         <div class="box"><img src="images/girl.jpg" /></div>
15     </div>
16     <script type="text/javascript">
17     var maxWidth = 200,
18         maxHeight = 200,
19         imgs = document.getElementById("imgList").getElementsByTagName("img");
20     for(var i=0; i<imgs.length; i++) {
21         imgs[i].onload = fixImg;
22     }
23     function fixImg() {
24         var image = new Image();
25         image.src = this.src;
26         if(image.width>0 && image.height>0) {
27             var rate = (maxWidth/image.width < maxHeight/image.height)?maxWidth/image.width:maxHeight/image.height;
28             if(rate<=1) {
29                 this.width = image.width*rate;
30                 this.height = image.height*rate;
31             }
32             else {
33                 this.width = image.width;
34                 this.height = image.height;
35             }
36         }
37     }
38     </script>
39 </body>
40 </html>
posted @ 2012-05-14 11:50  长风freedom  阅读(245)  评论(0编辑  收藏  举报