【问题标题】:Scale image properly but fit inside div正确缩放图像但适合 div
【发布时间】:2016-08-10 23:58:06
【问题描述】:

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

【问题讨论】:

  • @JohnJohnGa 这是一个完全不同的问题。我不想要滚动条。我想调整我的图像大小。我也没有使用 JQuery。
  • 啊,我给出了一个调整它们大小的答案,但是在 jquery 中。我已经删除了。
  • @popnoodles 别等了!那很有帮助。我可以将其更改为香草 JS。取消删除它,我会接受它:)
  • 哦,好的。我忘记了如何使用香草遍历父级。如果你知道你在做什么没问题。

标签: javascript html css image


【解决方案1】:

jquery example

最适合:

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

【讨论】:

  • 谢谢,您的解决方案帮助了我。只是一个问题,这是否适用于所有这些条件: 1. 图像大于父级? 2. 图像小于父级? 3.Image等于父级?
  • @Rutwick 是的,确实如此。
  • 这很棒,很紧凑,正是我想要的。谢谢。
  • 任何想要使用它的人,请注意api.jquery.com/load-event上的“与图像一起使用时加载事件的注意事项”
【解决方案2】:

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

Fiddle example

【讨论】:

  • 请注意,如果可以在 CSS 中完成,使用 jquery 进行设计是一种不好的做法。
  • 这是有道理的,我同意如果它可以用 CSS 完成,最好这样做,但如果图像小于 div,它就不起作用。
  • 让它宽度为 100% :p
  • 如果结果高度大于 div 的高度,将宽度设为 100% 会导致其溢出
  • 你检查过这个例子吗?他们是无法让它溢出其包含的 div 并且它将始终保持其纵横比。
猜你喜欢
  • 2015-07-14
  • 2021-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-25
  • 2023-03-16
  • 1970-01-01
  • 2014-05-31
相关资源
最近更新 更多