js等比例缩放图片

来源:互联网 发布:返利网是淘宝的吗 编辑:程序博客网 时间:2024/05/16 05:38

 

有时网页很容易被大图片撑开,下面的js小技巧可以用来解决这个问题。js获得图片大小和容器的大小进行比较然后重新设置图片的显示大小,示例如下:
Code:
  1. 有时网页很容易被大图片撑开,下面的小技巧可以用来解决这个问题:  
  2.  <script language="JavaScript" type="text/javascript">  
  3.   
  4. function DrawImage(ImgD,FitWidth,FitHeight){  
  5.      var image=new Image();  
  6.      image.src=ImgD.src;  
  7.      if(image.width>0 && image.height>0){  
  8.          if(image.width/image.height>= FitWidth/FitHeight){  
  9.              if(image.width>FitWidth){  
  10.                  ImgD.width=FitWidth;  
  11.                  ImgD.height=(image.height*FitWidth)/image.width;  
  12.              }else{  
  13.                  ImgD.width=image.width;   
  14.                 ImgD.height=image.height;  
  15.              }  
  16.          } else{  
  17.              if(image.height>FitHeight){  
  18.                  ImgD.height=FitHeight;  
  19.                  ImgD.width=(image.width*FitHeight)/image.height;  
  20.              }else{  
  21.                  ImgD.width=image.width;   
  22.                 ImgD.height=image.height;  
  23.              }   
  24.         }  
  25.      }  
  26.  }  
  27.   
  28.  </script>  
  29.   
  30.   
  31. <img src="1.jpg" alt="自动缩放后的效果"  onload="javascript:DrawImage(this,400,180);" />  
传容器的宽和高给DrawImage函数就会得到合适大小等比例缩放的图片。