码迷,mamicode.com
首页 > Web开发 > 详细

图片等比缩放js

时间:2015-03-06 16:53:29      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

<!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>

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

图片等比缩放js

标签:

原文地址:http://www.cnblogs.com/thekingofreturn/p/4318658.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!