javascript图片自动缩放和垂直居中处理函数
2010-09-14 13:28:33 来源:WEB开发网<html>
注释:
<head>
<title>Untitled</title>
<style type="text/css">
.testCss{width:200px;height:300px;border:1px red solid;text-align:center;display:block;}
.testCss1{width:300px;height:300px;border:1px red solid;text-align:center;display:block;}
.testCss2{width:400px;height:300px;border:1px red solid;text-align:center;display:block;}
</style>
<script type="text/javascript">
function autoSizeImg(Contents,offsetWidth,offsetHeight,vlmiddle){
var o=Contents.getElementsByTagName("IMG");
var cwidth= window.getComputedStyle?window.getComputedStyle(Contents,null).width:Contents.currentStyle["width"];
var cheight=window.getComputedStyle?window.getComputedStyle(Contents,null).height:Contents.currentStyle["height"];
var ncwidth=parseInt(cwidth);
var ncheight=parseInt(cheight);
for(var i=0;i<o.length;i++){
var img=o[i];
var iw=img.width;
var ih=img.height;
if(img.width>ncwidth){
var nw=ncwidth-offsetWidth;
img.width=nw
img.height=(nw*ih)/iw;
}else if(img.width<ncwidth&&img.height>ncheight){
var nh=ncheight-offsetHeight;
img.height=nh;
img.width=(nh*iw)/ih;
}
if(img.height>ncheight&&img.width<ncwidth){
var hh=ncheight-offsetHeight;
img.height=nh;
img.width=(nh*iw)/ih;
}
if(vlmiddle)img.style.marginTop=((ncheight-img.height)/2)+"px";
}
}
</script>
</head>
<body>
<div class="testCss">
<img src=http://tech.ddvip.com/2008-12/"http://files.jb51.net/file_images/sucai/111131524.jpg" onload="autoSizeImg(this.parentNode,5,5,true)"/>
</div>
<div class="testCss1">
<img src=http://tech.ddvip.com/2008-12/"/upload/20081010215957304.jpg" onload="autoSizeImg(this.parentNode,5,5,true)"/>
</div>
<div> </div>
<div class="testCss2">
<img src=http://tech.ddvip.com/2008-12/"/upload/20081010215958874.gif" onload="autoSizeImg(this.parentNode,5,5,true)"/>
</div>
</body>
</html>
Tags:javascript 图片 自动
编辑录入:爽爽 [复制链接] [打 印]更多精彩
赞助商链接