我试图在我的类 img-wrap 中获取每个图像的宽度,并将该宽度应用于每个元素的 img-caption 类。 我下面的代码仅适用于第一项。
<div class="img-wrap">
<img src="http://lorempixel.com/300/100" />
<div class="img-caption">aa</div>
</div>
<div class="img-wrap">
<img src="http://lorempixel.com/400/100" />
<div class="img-caption"></div>
</div>
<div class="img-wrap">
<img src="http://lorempixel.com/500/100" />
<div class="img-caption">cc</div>
</div>
<script>
var imgwidth = 0;
$('.img-wrap').each(function (index, value) {
imgwidth = $('.img-wrap img').width();
if ($('.img-caption').text() === '') {} else {
$(this).css("background-color", "#000");
$(this).css("color", "#fff");
$(this).css("width", imgwidth);
}
});
</script>
然后该宽度将应用于所有类。我在这里缺少什么来获得应用于每个 img-caption 的宽度。 例如,在我的示例中,不是它们都是 300 像素宽,因为这是第一张图像的宽度,它们应该是 300,400,500。我有 else 之类的,因为我可能稍后会在 if 中添加一些与问题无关的内容。
最佳答案
关于javascript - jquery获取每张图片的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20038158/