我有 3 个图像 block ,上面有文字。这是 3 种之一的外观。
<div class="lp">
<h2 class="align-vert">
This is my title
</h2>
</div>
我想在 jQuery 中获取标题 height();
并将其应用于 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();
});
关于javascript - 获取每个元素获取高度并将其应用为 margin-top,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41130205/