ti faccio un esempio che vale più di tante parole
codice:
<HTML>
<HEAD>
<title>Ridimensionamento proporzionato</title>
<script language="javascript">
function Init(){
var ff = document.FormDati
var dd = document.getElementById('contenitore')
ff.ContenitoreW.value=dd.style.width
ff.ContenitoreW.value=ff.ContenitoreW.value.replace(/[^\d]/g,'');
ff.ContenitoreH.value=dd.style.height
ff.ContenitoreH.value=ff.ContenitoreH.value.replace(/[^\d]/g,'');
dd = document.getElementById('contenuto')
ff.ContenutoW.value=dd.style.width
ff.ContenutoW.value=ff.ContenutoW.value.replace(/[^\d]/g,'');
ff.ContenutoH.value=dd.style.height
ff.ContenutoH.value=ff.ContenutoH.value.replace(/[^\d]/g,'');
}
window.onload=Init
function proporzioni(x,y,xmax,ymax){
if(parseInt((ymax*x)/y)<xmax){
this.newY = ymax
this.newX = parseInt((ymax*x)/y)
}
else{
this.newX = xmax
this.newY = parseInt((xmax*y)/x)
}
}
function adatta(ff){
var x = parseInt(ff.ContenutoW.value,10);
var y = parseInt(ff.ContenutoH.value,10);
var maxx = parseInt(ff.ContenitoreW.value,10);
var maxy = parseInt(ff.ContenitoreH.value,10);
var pp = new proporzioni(x,y,maxx,maxy);
ff.ContenutoW.value=pp.newX;
ff.ContenutoH.value=pp.newY;
ridisegna(ff);
}
function ridisegna(ff){
var dd = document.getElementById('contenitore')
dd.style.width=ff.ContenitoreW.value
dd.style.height=ff.ContenitoreH.value
dd = document.getElementById('contenuto')
dd.style.width=ff.ContenutoW.value
dd.style.height=ff.ContenutoH.value
}
</script>
</HEAD>
<body>
<form name="FormDati">
Contenitore W <input type="text" name="ContenitoreW">
Contenitore H <input type="text" name="ContenitoreH">
Contenuto W <input type="text" name="ContenutoW">
Contenuto H <input type="text" name="ContenutoH">
<input type="button" value="ridisegna" onclick="ridisegna(this.form);">
<input type="button" value="adatta" onclick="adatta(this.form);">
</form>
<hr>
<div id="contenitore" style="background-color:red;width:200px;height:300;">
<div id="contenuto" style="background-color:yellow;width:50px;height:30;"></div>
</div>
</body>
</html>