$(document).ready(function() {
var $drawer = $('.sc-drawer');
$drawer.find( '.sc-drawer-dropdown' ).each( function () {
var $this = $( this ),
$dropdown = $this.closest('.sc-dropdown'),
$height = $dropdown.css('height');
console.log($height);
});
});

a {
height: 48px;
line-height: 48px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="sc-drawer">
<a href="#" class="sc-drawer-dropdown">parent</a>
<div class="sc-dropdown">
<a href="/">Sub</a>
<a href="/">Sub</a>
</div>
<a href="#" class="sc-drawer-dropdown">parent</a>
<div class="sc-dropdown">
<a href="/">Sub</a>
</div>
</nav>
&#13;
在示例中,子元素是并排的,但对我来说,它们是堆叠/在彼此之下。
所以我希望$height
为92px
和48px
,但我得到的都是未定义的。
如何使$height
返回预期结果?我还尝试使用$dropdown.height()
,但也会返回null
/ undefined
答案 0 :(得分:2)
.closest()
遍历DOM;试试.next()
。顺便说一下,它们都会返回与内联元素相同的高度。如果它们是块级别,你将获得X和2X。
$(document).ready(function() {
var $drawer = $('.sc-drawer');
$drawer.find('.sc-drawer-dropdown').each(function() {
var $this = $(this),
$dropdown = $this.next('.sc-dropdown'),
$height = $dropdown.css('height');
console.log($height);
});
});
a {
height: 48px;
line-height: 48px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="sc-drawer">
<a href="#" class="sc-drawer-dropdown">parent</a>
<div class="sc-dropdown">
<a href="/">Sub</a>
<a href="/">Sub</a>
</div>
<a href="#" class="sc-drawer-dropdown">parent</a>
<div class="sc-dropdown">
<a href="/">Sub</a>
</div>
</nav>