2011-11-16 8 views

risposta

7

L'unica soluzione affidabile è quello di utilizzare un formula to determine maximum scale ratio:

var $img = $('#content img'), 
    imageWidth = $img[0].width, //need the raw width due to a jquery bug that affects chrome 
    imageHeight = $img[0].height, //need the raw height due to a jquery bug that affects chrome 
    maxWidth = $(window).width(), 
    maxHeight = $(window).height(), 
    widthRatio = maxWidth/imageWidth, 
    heightRatio = maxHeight/imageHeight; 

var ratio = widthRatio; //default to the width ratio until proven wrong 

if (widthRatio * imageHeight > maxHeight) { 
    ratio = heightRatio; 
} 

//now resize the image relative to the ratio 
$img.attr('width', imageWidth * ratio) 
    .attr('height', imageHeight * ratio); 

//and center the image vertically and horizontally 
$img.css({ 
    margin: 'auto', 
    position: 'absolute', 
    top: 0, 
    bottom: 0, 
    left: 0, 
    right: 0 
}); 
+0

Ho provato questo, ma non mantiene le proporzioni :(Ottengo l'altezza massima, ma le immagini ampie vengono schiacciate :( –

1

Se si dispone al di fuori di tutti gli elementi si può semplicemente utilizzare i CSS: <img src="something.jpg" style="width:100%; height:100%" onload="scaleToFullScreen()" />

se non lo fai:

<img name='myImage' src="something.jpg" onload="onResize()" /> 
<script> 
window.onresize = onResize; 

function onResize(e){ 
    var img = var img = document.images.myImage; 
    if (img.width > img.height) 
     img.width = window.innerWidth 
    else 
     img.height = window.innerHeight; 
} 
</script>
+0

che non sarebbe proporzionato. Devo "ridimensionarlo", non distorcerlo. – Andrew

+0

@Andrew quindi se la finestra non ha le stesse proporzioni, dovrebbe [letterbox] (http://en.wikipedia.org/wiki/Letterbox)? – Nicole

+0

@ Renesis In sostanza, sì. – Andrew