gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:55:46 25 4
gpt4 key购买 nike

我有一个包含多个列表的网页。 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com