利用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>testDemo</title>
<style type="text/css">
.productlist .productImage
{
width:180px;
height:120px;
border:1px solid #eee;
display: table-cell;
vertical-align:middle;
text-align:center;
*display: block;
*font-size: 105px;/*约为高度的0.873,200*0.873 约为175*/
*font-family:Arial;
margin-bottom:15px;
}
.productlist .productImage img
{
vertical-align:middle;
}
</style>
</head>
<body>
<ul class="productlist" name="main" id="Img_lists">
<li><a href="ProductDetail.aspx?ProductID={products[ID]}" target="_top">
<div class="productImage">
<img class="imgProducts" alt='{products[Name]}' src='http://www.cnblogs.com/..{products[ImgPath]}'
runat="server" />
</div>
<h4 class="pro_name">
{products[Name]}
</h4>
<h4 class="price">
单价¥:{products[Price]}/{products[Unit]}</h4>
</a></li>
</ul>
<script type="text/javascript">
function imgChange(){
var oDiv=document.getElementById("Img_lists");
var oImage=oDiv.getElementsByTagName("img");
var maxWidth=180;
var maxHeight=120;
var rW=maxWidth/maxHeight;
for(var i=0;i<oImage.length;i++){
if(oImage[i].width>0&&oImage[i].height>0){
var sW=oImage[i].width/oImage[i].height;
if(oImage[i].width/oImage[i].height>=rW){
if(oImage[i].width>maxWidth){
oImage[i].width=maxWidth-1;
oImage[i].height=oImage[i].width/sW;
}
}else{
if(oImage[i].height>maxHeight){
oImage[i].height=maxHeight-1;
oImage[i].width=oImage[i].height*sW;
}
}
}
}
}
imgChange();
</script>
</body>
</html>
浙公网安备 33010602011771号