javascript 根据图片实际比例进行缩放, 并居中显示, 用到jQuery

[b][color=orange]并未进行广泛的测试[/color][/b]


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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值