我有这样一个简单的 html 代码:
<section class="main">
<div class="container">
<div class="row">
<header class="verticalCenter">
...
</header>
</div>
</div>
</section>
另外,我有这个 jQuery:
function verticalCenter(el) {
el.each(function() {
var elHeight = $(this).outerHeight(true),
parentHeight = $(this).parent('section').outerHeight(true),
marginTop = (parentHeight - elHeight)/2;
$(this).css('margin-top',marginTop);
})
}
verticalCenter($('.verticalCenter'))
问题是 - jQuery 没有看到 section.main
。我做错了什么?
最佳答案
你想要.closest()
,而不是.parent()
parentHeight = $(this).closest('section').outerHeight(true),
.parent()
函数仅检查直接父级。向它传递一个选择器有效地意味着,“给我父级,但前提是父级匹配这个选择器;否则,给我一个空列表。”
关于javascript - jQuery 无法获得顶级父级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18932108/