纯js实现div内图片自适应大小(已测试,兼容火狐)
废话不多说,直接上代码,已测试,兼容火狐,谷歌,IE6,IE7/8
以下是js代码:
<scripttype="text/javascript"language="javascript">
window.onload=function(){
changeImgSize();
}
functionchangeImgSize(){
vargetContainer=document.getElementById('imgcontainer');
vargetIMG=getContainer.getElementsByTagName('img')[0];
varfw=getContainer.offsetWidth-(2*getContainer.clientLeft);
varfh=getContainer.offsetHeight-(2*getContainer.clientTop);
variw=getIMG.width;
varih=getIMG.height;
varm=iw/fw;
varn=ih/fh;
if(m>=1&&n<=1)
{
iw=Math.ceil(iw/m);
ih=Math.ceil(ih/m);
getIMG.width=iw;
getIMG.height=ih;
}
elseif(m<=1&&n>=1)
{
iw=Math.ceil(iw/n);
ih=Math.ceil(ih/n);
getIMG.width=iw;
getIMG.height=ih;
}
elseif(m>=1&&n>=1)
{
getMAX=Math.max(m,n);
iw=Math.ceil(iw/getMAX);
ih=Math.ceil(ih/getMAX);
getIMG.width=iw;
getIMG.height=ih;
}
if(getIMG.height<fh)
{
vargetDistance=Math.floor((fh-getIMG.height)/2);
getIMG.style.marginTop=getDistance.toString()+"px";
}
}
</script>
以下是html代码:
<divid="imgcontainer"><imgsrc="images/444.jpg"/></div>
以下是css代码:
.sy_pic{width:200px;height:300px;border:#000solid5px;text-align:center;}
自己换下图片地址使用。有问题或者指教请加QQ群:255708401。