图像调整大小以适应屏幕 [英] Image resize to fit screen
问题描述
我创建此代码以调整照片/图像的大小以适应屏幕,考虑到导航栏的可用空间。
I created this code to resize photos/images to fit the screen, considering the space available for the nav bar.
脚本在图像加载和导航时触发点击。
The script fires on image load and on navigation click.
有没有人建议改善这一点并确保浏览器兼容性?
Does anyone have suggestions as to making this better and ensuring browser compatibility?
$(document).ready(function(){
$("#photo").load(function(){
resize();
});
$(".navigation img").click(function(){
var imgPath = $(this).attr("src");
$("#photo").attr({ src: imgPath });
resize();
return false;
});
});
Javascript
Javascript
resize = function() {
var borderVt=150; //value based on css style. bottom bar + padding of photoContain
var borderHz=40; //value based on css style photoContain padding
$("#photo").css("width", "auto").css("height", "auto"); // Remove existing CSS
$("#photo").removeAttr("width").removeAttr("height"); // Remove HTML attributes
var origSizeW = $("#photo").width();
var origSizeH = $("#photo").height();
var ratioVt=(origSizeW/origSizeH);
var ratioHz=(origSizeH/origSizeW);
var winW = $(window).width();
var winH = $(window).height();
var screenSizeW=Math.round(winW-borderHz);
var screenSizeH=Math.round(winH-borderVt);
if (origSizeW>=origSizeH){
var newHeight = Math.round(screenSizeW*ratioHz);
if (newHeight <= screenSizeH){
$("#photo").css("width", screenSizeW); // Set new width
$("#photo").css("height", newHeight);
}
else{
$("#photo").css("height", screenSizeH);
}
}
else{
$("#photo").css("height", screenSizeH); // Set new height
}
};
推荐答案
我知道这个问题很老了,但是这里的 a 解决方案(虽然我确信OP的工作正常):
I know this question is well old, but here's a solution (although I'm sure the OP's works fine too):
这个jQuery插件似乎正是你所需要的:
http://code.google.com/p/jquery-imagefit-plugin/
This jQuery plugin seems to do exactly what you need: http://code.google.com/p/jquery-imagefit-plugin/
如果你在100%高度,100%宽度元素上执行它:
http://www.tutwow.com/htmlcss/quick-tip-css-100-height/
if you perform it on a 100% height, 100% width element: http://www.tutwow.com/htmlcss/quick-tip-css-100-height/
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://jquery-imagefit-plugin.googlecode.com/svn/trunk/jquery.imagefit-0.2.js"></script>
<div style="width: 100%; height: 100%">
<img id="h5" src="http://www.w3.org/html/logo/downloads/HTML5_Logo_512.png"/>
</div>
<script>
jQuery('#h5').bind('load', function() {
jQuery('div').imagefit();
});
</script>
(演示: http://jsfiddle.net/nottrobin/9Pbdz/ )
这篇关于图像调整大小以适应屏幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!