我想获取下例中 .child
类的高度值,然后使用警报显示该值以进行故障排除。
我有两个同级元素 .first
和 .second
,.second
元素有一个名为 .child 的子元素
HTML:
<div class="parent">
<div class="first">Click Me</div>
<div class="second">
<div class="child"></div>
</div>
</div>
CSS:
.first {
width: 60px;
padding: 8px;
background: blue;
}
.child {
height: 1234px;
}
jQuery:
$(".first").click(function() {
var childHeight = $(this).next(".second > .child").outerHeight();
alert(childHeight);
});
问题似乎在于针对子项,如果我从我的变量中删除 > .child
,它会返回 .second
的高度
这是一个具有相同代码的 JS fiddle :https://jsfiddle.net/CultureInspired/6dxLp86b/
最佳答案
您应该使用 .next(".second").find(".child")
来正确获取子元素。
这将获取下一个元素,然后在其中找到 .child
元素。
$(".first").click(function() {
var childHeight = $(this).next(".second").find(".child").outerHeight();
alert(childHeight);
});
.first {
width: 60px;
padding: 8px;
background: blue;
}
.child {
height: 1234px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<div class="first">Click Me</div>
<div class="second">
<div class="child"></div>
</div>
</div>
关于javascript - 目标下一个 sibling 的 child 获得外部高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49072818/