简体   繁体   English

获取每个元素的高度,并将其应用为margin-top

[英]Get each element get height and apply it as margin-top

I have 3 blocks of images with text on top of them. 我在其上有3个带有文字的图像块。 Here is how one of the 3 looks like. 这是三者之一的样子。

<div class="lp">
    <h2 class="align-vert">
        This is my title
    </h2>
</div>

I want to get the title height(); 我想获得标题height(); in jQuery and apply it to the aligh-v . 在jQuery中并将其应用于aligh-v I tried the following jQuery code but it doesn't work. 我尝试了以下jQuery代码,但没有用。

jQuery.each(jQuery('.js-vert'), function() {
    jQuery(this).css({
        "margin-top": '"' + jQuery('.js-vert').height() + '"'
    });
});

The issue is because you need to use the this reference within the each() method to refer to the current element. 问题是因为您需要在each()方法中使用this引用来引用当前元素。 As it stands, your code is calling height() the entire set of elements which means only the height of the first element is returned. 就目前而言,您的代码正在调用整个元素集的height() ,这意味着仅返回第一个元素的高度。 Your syntax of string concatenation is also a little off. 您的字符串连接语法也有些不足。 Try this: 尝试这个:

$('.js-vert').each(function() {
    $(this).css("margin-top", $(this).height());
});

Also note that this can be made more succinct by removing the each() loop entirely and passing a function to the css() method which returns the value needed: 还请注意,可以通过完全删除each()循环并将函数传递给css()方法来使其更加简洁,该方法返回所需的值:

$('.js-vert').css('margin-top', function() {
    return $(this).height();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM