我有一張圖片可以縮放到全屏。我將如何使用JavaScript/jQuery來做到這一點?不需要動畫,只需調整圖像大小。如何使用JavaScript將圖像縮放爲全屏?
<img src="something.jpg" onload="scaleToFullScreen()" />
我有一張圖片可以縮放到全屏。我將如何使用JavaScript/jQuery來做到這一點?不需要動畫,只需調整圖像大小。如何使用JavaScript將圖像縮放爲全屏?
<img src="something.jpg" onload="scaleToFullScreen()" />
唯一可靠的解決方案是使用一個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
});
我試過這個,但它不保持長寬比:(我得到最大高度,但寬圖像被壓扁:( –
如果你擁有了它,你可以只使用CSS的所有元素之外: <img src="something.jpg" style="width:100%; height:100%" onload="scaleToFullScreen()" />
如果你不這樣做:
<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>
Full * screen * or full * window *? – Nicole
整個窗口。 =] – Andrew