2009/12/31 19:12:22

网页图片自动按比例缩小代码(防止页面被图片撑破)

网页图片自动按比例缩小代码(防止页面被图片撑破)

<div id=article><img height="800" alt="" width="1280" src="/down/js/images/12498880470.jpg" /></div>
<script type="text/javascript" >

//缩放图片到合适大小
function ResizeImages()
{
   var myimg,oldwidth,oldheight;
   var maxwidth=550;
   var maxheight=880
   var imgs = document.getElementById('article').getElementsByTagName('img');   //如果你定义的id不是article,请修改此处

   for(i=0;i<imgs.length;i++){
     myimg = imgs[i];

     if(myimg.width > myimg.height)
     {
         if(myimg.width > maxwidth)
         {
            oldwidth = myimg.width;
            myimg.height = myimg.height * (maxwidth/oldwidth);
            myimg.width = maxwidth;
         }
     }else{
         if(myimg.height > maxheight)
         {
            oldheight = myimg.height;
            myimg.width = myimg.width * (maxheight/oldheight);
            myimg.height = maxheight;
         }
     }
   }
}
//缩放图片到合适大小
ResizeImages();
</script>