我有3块图像,上面有文字.以下是3个中的一个.
<div class="lp">
<h2 class="align-vert">
This is my title
</h2>
</div>
Run Code Online (Sandbox Code Playgroud)
我想height();在jQuery中获取标题并将其应用于aligh-v.我尝试了以下jQuery代码,但它不起作用.
jQuery.each(jQuery('.js-vert'), function() {
jQuery(this).css({
"margin-top": '"' + jQuery('.js-vert').height() + '"'
});
});
Run Code Online (Sandbox Code Playgroud)
问题是因为您需要使用方法中的this引用each()来引用当前元素.就目前而言,您的代码调用height()整个元素集,这意味着只返回第一个元素的高度.你的字符串连接语法也有点过时了.试试这个:
$('.js-vert').each(function() {
$(this).css("margin-top", $(this).height());
});
Run Code Online (Sandbox Code Playgroud)
还要注意,通过each()完全删除循环并将函数传递给css()返回所需值的方法,可以使这更加简洁:
$('.js-vert').css('margin-top', function() {
return $(this).height();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36 次 |
| 最近记录: |