jQuery - 将 CSS 应用于匹配的项目



我有一个看起来像这样的html布局。

<div class="container>
<div class="panel">
<div>
<div>
<div>
<img class="match" src="myimage.jpg">
</div>
</div>
</div>
</div>
<div class="panel">
<div>
<div class="item">
<div class="img_container">
<img class="match">
</div>
</div>
</div>
</div>
</div>

我正在尝试修改它,使其看起来像这样。

<div class="container style="align-items: stretch;">
<div class="panel">
<div>
<div>
<div>
<img class="match" src="myimage.jpg">
</div>
</div>
</div>
</div>
<div class="panel">
<div style="height: 100%;">
<div class="item style="height:  100%;">
<div class="img_container" style="height:  100%;">
<img class="match" src="myimage.jpg">
</div>
</div>
</div>
</div>
</div>

我已经研究了CSS选择器,但我认为它们在这种情况下不适合我。

如何使用jQuery执行此操作? 我希望它检测容器类是否存在,然后将 CSS 应用于项目。

我猜是这样的。请尝试一下它是否有效

// if el with container class exists will add align-item css
// $('.container').css('align-items','stretch');
// updated, will only apply 'align-items' on container which contains img with class 'match'
$('img.match').closest('.container').css('align-items','stretch');
// assign div with item class, its div parent, and img_container class with height:100%
$('.item').css('height','100%');
$('.img_container').css('height','100%');
$('.item').closest('div').css('height','100%');
// get the src of the first img el with class "match" and assign it to the 2nd img el with class "match"
var src = $('.match').first().attr('src');
if(src){ 
$('.match').last().attr('src',src);
}

最新更新