jQuery根据最近图像的宽度改变div的宽度?

时间:2014-06-10 15:36:48

标签: jquery css

我有一个具有以下结构的ul:

<ul>
<li><img><div class="infotext">some variable length text</div></li>
<li><img><div class="infotext">some variable length text</div></li>
<li><img><div class="infotext">some variable length text</div></li>
<ul>

图像根据窗口高度被赋予动态高度,并且它们的宽度是自动的(并且可变,我的图像具有不同的比例,但我保持它们的高度相同),所以我想制作我的信息文本div匹配此变量宽度。我尝试过以下方法:

jQuery('.infotext').width(jQuery(this).closest('img').width());

jQuery('.infotext').width(jQuery('.infotext').closest('img').width());

jQuery('.infotext').width(jQuery('.infotext').parent().width());

但他们都没有工作。到目前为止,我很难过......

更新 我已经弄明白是什么导致了这个问题,但不知道解决方案是什么。我的图像使用延迟加载,这妨碍了获得正确的图像高度。我需要弄清楚如何在延迟加载后获取图像大小...

3 个答案:

答案 0 :(得分:1)

图片标记是前一个元素,而不是祖先,因此.closest().parent()将不起作用。

尝试:

jQuery('.infotext').each(function(){
    $(this).width(jQuery(this).prev('img').width());
})

<强> jsFiddle example

答案 1 :(得分:0)

closest()用于查找父元素。在这种情况下,您需要prev()

jQuery('.infotext').width(function() {
    return $(this).prev('img').width();
});

Example fiddle

答案 2 :(得分:0)

哇,多么糟糕(但是学习机会很好)。问题原来是:

  1. 我无法获得这些元素的宽度和高度,可能是由于延迟加载它们。自从我根据窗户高度设置它以后,我能够独自拉高度。

  2. 因为高度和宽度会根据我的窗口大小而改变,并且之前的图像没有设置大小,所以我很难获得计算所需的值。

  3. <强>解决方案

    可能有更好的方法可以做到这一点,但这就是我想出来的,它最终有效:

    首先,我将原始宽度和高度作为数据属性添加到每个图像中,如下所示:

    <img src="lazyload.gif" data-original="path/to/my/originalfile.jpg" data-original-width="<?php echo $image_attributes["width"]; ?>" data-original-height="<?php echo $image_attributes["height"]; ?>" />
    

    然后在我的jQuery中,我根据添加到图像中的样式(取决于窗口的高度)进行计算,并将其与原始高度进行比较,以获得我的公式来转换原始宽度:

    jQuery('.infotext').each(function(){
        var newWidthCalc = (jQuery(this).prev('img').attr( "data-original-height" )/jQuery(this).prev('img').css("height").replace('px', ''));
        var newWidth = (jQuery(this).prev('img').attr( "data-original-width" )/newWidthCalc);
        newWidth = (parseInt(newWidth)-30) + 'px'; //remove 30 pixels so a little smaller
        jQuery(this).css('width',newWidth);
        }
    });
    

    最后,它有效!