[英]Scale image properly but fit inside div
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? 有没有办法可以检查我的Javascript中是否有溢出? Something like this:
像这样的东西:
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
?
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');
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.