The function implemented by this code is that when a div we usually encounter contains img, when the img image size is unknown and the div size is unknown, the image adaptively size is not processed when the image itself is smaller than the div container size. Because if stretched, the picture may be distorted.
Without further ado, just upload the code, tested, compatible with Firefox, Google, IE6, IE7/8
The following is the js code:
The code copy is as follows:
<script type="text/javascript" language="javascript">
window.onload=function(){
changeImgSize();
}
function changeImgSize(){
var getContainer=document.getElementById('imgcontainer');
var getIMG=getContainer.getElementsByTagName('img')[0];
var fw=getContainer.offsetWidth-(2*getContainer.clientLeft);
var fh=getContainer.offsetHeight-(2*getContainer.clientTop);
var iw=getIMG.width;
var ih=getIMG.height;
var m=iw/fw;
var n=ih/fh;
if(m>=1&&n<=1)
{
iw=Math.ceil(iw/m);
ih=Math.ceil(ih/m);
getIMG.width=iw;
getIMG.height=ih;
}
else if(m<=1&&n>=1)
{
iw=Math.ceil(iw/n);
ih=Math.ceil(ih/n);
getIMG.width=iw;
getIMG.height=ih;
}
else if(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)
{
var getDistance=Math.floor((fh-getIMG.height)/2);
getIMG.style.marginTop=getDistance.toString()+"px";
}
}
</script>
The following is the html code:
The code copy is as follows:
<div id="imgcontainer"><img src="images/444.jpg" /></div>
Here is the css code:
The code copy is as follows:
.sy_pic{ width:200px; height:300px; border:#000 solid 5px; text-align:center;}
Change the image address yourself to use. If you have any questions or advice, please add the QQ group: 255708401.