日期:2014-05-16  浏览次数:20470 次

javascript 根据图片实际比例进行缩放, 并居中显示, 用到jQuery
并未进行广泛的测试

<html>
<head>
<title>根据图片实际比例进行缩放</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="study/global.js"></script>
<style>body{font-size:12px;}</style>
</head>
<body>
<p id="pic" style=" width:550px; height:500px; border:solid 1px #f60; overflow:hidden;">
	<img src="http://www.baidu.com/img/baidu_sylogo1.gif" width="100" height="400" align="center" height="" />
</p>
<input type="button" value="生成CMD" id="go" onclick="PicUtil.fixCenter($('#pic'))" />
<br><br>
<div id="msg"></div>
<script type="">

var PicUtil={
	cacheImg:$('<img />'),
	//以容器为基准, 根据图片实际比例进行缩放
	fixCenter:function(box){
		var img=$("img",$(box));
		if(img.size()>0){
			var o = this.getProperty(img[0]);
			if(o.wf>o.w0 && o.hf>o.h0){
				this.fixOnly(box);
			}else if(o.wf<o.w0 || o.hf<o.h0){
				img.width(o.wf).height(o.hf);
				if(o.hp>o.hf) $('<div style="clear:both;width:1px;height:'+((o.hp-o.hf)/2)+'px"></div>').insertBefore(img);
				if(o.wp>o.wf) $(box).css("text-align","center");
			}
		}
	},
	fixOnly:function(box){
		var img=$("img",$(box));
		if(img.size()>0){
			$(box).css({"background-image":"url("+img[0].src+")","background-repeat":"no-repeat","background-position":"center"}).empty();
		}
	},
	getProperty:function(img){
		if(!img || !img.src) return {};
		var tmpImg=this.cacheImg;
		tmpImg[0].src=img.src+"";
		var parent=$(img).parent();
		var rs={w0:tmpImg[0].width,h0:tmpImg[0].height,w:img.width,h:img.height,wp:parent.width(),hp:parent.height()};
		if(rs.w0==0 || rs.h0==0) return {};
		rs.wf=Math.floor(rs.h0/rs.w0*rs.wp)>rs.hp?(Math.floor(rs.w0/rs.h0*rs.hp)):rs.wp;
		rs.hf=Math.floor(rs.h0/rs.w0*rs.wp)>rs.hp?rs.hp:Math.floor(rs.h0/rs.w0*rs.wp);
		return rs;
	}
	
}


function msg(x,y){
	if(!y) $("#msg").html(x); else $("#msg").html(x+"<br>"+$("#msg").html());
}
</script>

</body>
</html>