如何在保持纵横比的同时将图像升级为始终覆盖div?

时间:2016-09-11 15:20:17

标签: javascript jquery html css

我希望我的内联图片的行为类似于background-size: cover;使用新属性object-fit: cover,这项功能非常出色,我想提供一个后备广告。

我已在下面创建了此回退的基本设置。唯一的问题是,我需要jQuery / Javascript来选择天气图像需要:width: 100%; height: auto;height: 100%; width: auto;。我怎么能这样做?

$('div').each(function() {
  var div = $(this);
  var image = div.find('img');
  
  // if image does not cover the div, change its css to { height: 100%; width: auto;}
});
div {
  width: 400px;
  height: 200px;
  margin-bottom: 50px;
  position: relative;
  overflow: hidden;
  background: lightblue;
}
img {
  width: 100%;
  height: auto;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Both divs should be covered by their images, while keeping the aspect ratio:

<div>
  <img src="http://placehold.it/600x100">
</div>
<div>
  <img src="http://placehold.it/100x600">
</div>

0 个答案:

没有答案