2011-11-16 34 views
6

Tôi có một hình ảnh mà tôi muốn chia tỷ lệ thành toàn màn hình. Làm thế nào tôi sẽ làm điều này bằng cách sử dụng JavaScript/jQuery? Không có hoạt ảnh là cần thiết, chỉ cần thay đổi kích thước hình ảnh.Làm cách nào để chia tỷ lệ hình ảnh thành toàn màn hình bằng JavaScript?

<img src="something.jpg" onload="scaleToFullScreen()" /> 
+3

Toàn màn hình * hoặc toàn bộ * cửa sổ *? – Nicole

+0

toàn cửa sổ. =] – Andrew

Trả lời

7

Các giải pháp đáng tin cậy duy nhất là sử dụng một 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

Tôi đã thử điều này nhưng nó không duy trì tỷ lệ khung hình: (Tôi nhận được chiều cao tối đa nhưng hình ảnh rộng bị đè bẹp :( –

1

Nếu bạn có nó bên ngoài của tất cả các yếu tố mà bạn chỉ có thể sử dụng css: <img src="something.jpg" style="width:100%; height:100%" onload="scaleToFullScreen()" />

nếu bạn không:

<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

sẽ không được cân xứng. Tôi cần phải "quy mô" nó, không nghiêng nó. – Andrew

+0

@Andrew vì vậy nếu cửa sổ không phải là cùng một tỷ lệ khung hình, nên nó [letterbox] (http://en.wikipedia.org/wiki/Letterbox)? – Nicole

+0

@Renesis Về cơ bản, có. – Andrew

Các vấn đề liên quan