繁体   English   中英

正确缩放图像但适合div内部

[英]Scale image properly but fit inside div

我正在制作一个图库。 这是图像的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 -->

当图像是正方形时,它可以正常工作,或者宽度不比高度多。 但是,当宽度太大时,它会断开。 图像溢出示例:

图像溢出

有没有办法可以检查我的Javascript中是否有溢出? 像这样的东西:

image.setAttribute('height', '100%')
image.removeAttribute('width')
if (image.isOverflowing()) {
    image.setAttribute('width', '100%')
    image.removeAttribute('height')
}

更好的是,是否有任何方法可以正确地缩放图像但是与包含div

jquery的例子

最适合:

$('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);
});

编辑以说明图像在缓存中的警告

$('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');

这是一个简单的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM