动态设置en元素的宽度以匹配相邻元素的宽度

时间:2013-12-16 04:32:01

标签: jquery html css

我的HTML如下:

<div class="row">
    <div class="image"><img src="" alt="" /></div>
    <div class="caption"></div>
</div>
<div class="row">
    <div class="image"><img src="" alt="" /></div>
    <div class="caption"></div>
</div>

我正在尝试将每个.caption的宽度设置为与.image img的高度相同

我是在正确的轨道上吗?

$(".caption").each(function(){
    var imgheight = $(this).closest(".image img").height();
    $(this).css({
        width: imgheight
    });
});

3 个答案:

答案 0 :(得分:1)

试试这个,

var imgheight = $(this).closest('.row').find(".image img").height();

var imgheight = $(this).prev(".image").find("img").height();

您也可以使用children()代替find()

closest()通过测试元素本身并遍历DOM树中的祖先来提供与选择器匹配的第一个元素。

答案 1 :(得分:1)

尝试:

var imgheight = $(this).parents(".row").find(".image img").height();

答案 2 :(得分:1)

试试这个

$(".caption").each(function(){
  var imgheight = $(this).parent().find(".image img").height();
  $(this).width(imgheight);
});

Live Demo