Pure js div image adaptive size of of has been tested compatible with firefox

  • 2020-03-30 03:23:06
  • OfStack

This code to achieve the function is usually we encounter a div containing img, img image size unknown, div size unknown, let the image adaptive size, for the image itself is less than the size of the div container, do not handle. Because if you stretch it, the picture may be distorted.

Nonsense, direct on the code, has been tested, compatible with firefox, Google, IE6, ie7/8

The following is the js code:
 
<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> 

Here is the HTML code:
 
<div class="sy_pic" id="imgcontainer"><img src="images/444.jpg" /></div> 

Here is the CSS code:
 
.sy_pic{ width:200px; height:300px; border:#000 solid 5px; text-align:center;} 

Change the image address by yourself. If you have any questions or comments, please add QQ group: 255708401.

Related articles: