图片等比缩放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>
<script type="text/javascript">
function AutoResizeImage(maxWidth,maxHeight,objImg){
	var img=new Image();
	img.src=objImg.src;
	var realHeight=img.height;//图片真实高度
	var realWidth=img.width;//图片真实宽度
    if(realWidth<maxWidth&&realHeight>maxHeight){
	     objImg.width=maxHeight*realWidth/realHeight;
		 objImg.height=maxHeight;
		 
    }
	else if(realWidth>maxWidth&&realHeight<maxHeight){
		objImg.width=maxWidth;
		objImg.height=realHeight*maxWidth/realWidth;
		 
	}
	else if(realWidth<=maxWidth&&realHeight<=maxHeight){
	 objImg.height=realHeight;
	 objImg.width=realWidth;
    }
    else{
		 var rateHeight=realHeight/maxHeight;
		 var rateWeight=realWidth/maxWidth;
		if(rateHeight<rateWeight)
		{
        objImg.width=maxWidth;
		  objImg.height=realHeight*maxWidth/realWidth;
		  
		}
		else
		{
		 objImg.height=maxHeight;
		 objImg.width=maxHeight*realWidth/realHeight;
		 
		}
  
	}
 	
 }
 
 
 </script>

</head>

<body>


<div style=" background:#f00; width:500px; height:800px;">
<img src="u.jpg" border=0  onload="javascript:AutoResizeImage(120,160,this)">
</div>

</body>



</html>

  虽然能实现等比缩放,总感觉代码太菜了。。。求指教。。。。

posted @ 2015-03-06 16:40  thekingofreturn  阅读(166)  评论(0编辑  收藏  举报