javascript 正确缩放图像但适合 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14425300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scale image properly but fit inside div
提问by Doorknob
I am making an image gallery. This is the HTML for the image:
我正在制作一个图片库。这是图像的 HTML:
<div style="width: 84%; height: 100%; float: left; text-align: center;"><img
id="mainimage" style="height: 100%;"
src="http://www.gymheroapp.com/workouts/img/spinner.gif"/></div>
<!-- Loading spinner is temp image, will be replaced by Javascript later -->
It works fine when the image is square, or the width is not too much more than the height. It breaks when the width is too great, though. Example of image overflowing:
当图像为方形,或者宽度不超过高度时,它工作正常。但是,当宽度太大时它会中断。图像溢出示例:
Is there a way I could check whether there is overflow within my Javascript? Something like this:
有没有办法可以检查我的 Javascript 中是否存在溢出?像这样的东西:
image.setAttribute('height', '100%')
image.removeAttribute('width')
if (image.isOverflowing()) {
image.setAttribute('width', '100%')
image.removeAttribute('height')
}
Even better, is there any way to scale the image properly but fit it withing the containing div
?
更好的是,有什么方法可以正确缩放图像但将其与包含的内容相匹配div
?
回答by Popnoodles
Best fit:
最适合:
$('img').on('load',function(){
var css;
var ratio=$(this).width() / $(this).height();
var pratio=$(this).parent().width() / $(this).parent().height();
if (ratio<pratio) css={width:'auto', height:'100%'};
else css={width:'100%', height:'auto'};
$(this).css(css);
});
Edit to account for caveat where image is in cache
编辑以说明图像在缓存中的位置
$('img').on('bestfit',function(){
var css;
var ratio=$(this).width() / $(this).height();
var pratio=$(this).parent().width() / $(this).parent().height();
if (ratio<pratio) css={width:'auto', height:'100%'};
else css={width:'100%', height:'auto'};
$(this).css(css);
}).on('load', function(){
$(this).trigger('bestfit');
}).trigger('bestfit');
回答by Chris Visser
Heres a simple CSS solution:
这是一个简单的 CSS 解决方案:
html, body { height: 100%; }
#gallery { height: 100%; width: 100%; position: relative; }
#gallery img {
/* CSS Hack will make it width 100% and height 100% */
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
/* Maintain aspect ratio */
max-height: 100%;
max-width: 100%;
}
<div id="gallery">
<img src="http://cl.vvmonnickendam.nl/files/large/87" alt="Awesome blabla gedoe">
</div>