[英]Get each element get height and apply it as margin-top
我在其上有3个带有文字的图像块。 这是三者之一的样子。
<div class="lp">
<h2 class="align-vert">
This is my title
</h2>
</div>
我想获得标题height();
在jQuery中并将其应用于aligh-v
。 我尝试了以下jQuery代码,但没有用。
jQuery.each(jQuery('.js-vert'), function() {
jQuery(this).css({
"margin-top": '"' + jQuery('.js-vert').height() + '"'
});
});
问题是因为您需要在each()
方法中使用this
引用来引用当前元素。 就目前而言,您的代码正在调用整个元素集的height()
,这意味着仅返回第一个元素的高度。 您的字符串连接语法也有些不足。 尝试这个:
$('.js-vert').each(function() {
$(this).css("margin-top", $(this).height());
});
还请注意,可以通过完全删除each()
循环并将函数传递给css()
方法来使其更加简洁,该方法返回所需的值:
$('.js-vert').css('margin-top', function() {
return $(this).height();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.