jquery - 如何根据包含的div的大小设置图像的大小?

标签 jquery html css image

我有一个包含多个列表的网页。 list 包括一张任意大小的图片,包裹图片的 DIV 的宽度和高度是固定的。如何在该 DIV 中填充图像。

<div class="image-wrap" style="width:150px;height:150px;">
<img src="some-image.png">
</div>

enter image description here

最佳答案

如果您坚持 OP 中的 HTML 结构,并且您愿意使用 jQuery 解决方案,则可以使用以下代码:

我在代码中添加了注释以阐明它。

$(function() {
  $('div').each(function() {
    var img = $(this).find('img'), /* find the image inside the div */
        imgUrl = img.attr('src'); /* get the image url */
    $(this).css('background-image', 'url('+imgUrl+')'); /* set the background image */
    img.remove(); /* remove the image inside the div */
  });
});
div {
  border: 1px solid red;
  margin: 1em;
  background-position: 50% 50%; /* center background image */
  background-size: cover; /* make the bg cover the whole element */
}

.div1 {
  width: 250px;
  height: 150px;
}

.div2 {
  width: 250px;
  height: 150px;
}

.div3 {
  width: 100px;
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div1">
  <img src="http://via.placeholder.com/350x150">
</div>
<div class="div2">
  <img src="http://via.placeholder.com/250x300">
</div>
<div class="div3">
  <img src="http://via.placeholder.com/350x150">
</div>

关于jquery - 如何根据包含的div的大小设置图像的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46468980/

相关文章:

javascript - 根据浏览器添加不同的HTML

javascript - 我们可以让一个元素(div)对鼠标事件透明吗?

jquery - 当 scrollTop 为 0 时做一些事情并且它仍然向上滚动(jQuery)

javascript - 如何使用 RegEx 排除以零开头的字母字符和数字?

html5 滑动事件

css - 如何并排垂直居中两个元素,然后使它们的内边距与垂直中心线等距?

javascript - 具有垂直行的 HTML 表格

html - Grails:在 gsp 中显示创建的图像

html - 基于 css html 的 slider /悬停时显示下一张幻灯片的一部分

javascript - 图像 slider 未加载 Ajax 请求