我有一个菜单。打开树时,它将获得类active
。我不想使用课程active
获得菜单中最深的子菜单。
答案 0 :(得分:1)
您可以使用parents()
集合计算元素的深度,然后返回特定选择器的最低值。试试这个:
<div>
1
<div class="active">1.1</div>
<div class="active">
1.2
<div class="active">
1.2.1
<div class="active">1.2.1.1</div>
</div>
<div class="active">1.2.2</div>
</div>
<div class="active">1.3</div>
<div class="active">
1.4
<div class="active">1.4.1</div>
<div class="active">1.4.2</div>
</div>
<div class="active">1.5</div>
</div>
var $elems = $('.active'), $deepest, lowestLevel = 0;
$elems.each(function() {
var depth = $(this).parents().length;
if (depth > lowestLevel) {
$deepest = $(this);
lowestLevel = depth;
}
});
$deepest.css('border', '1px solid #C00');
答案 1 :(得分:0)
还有香草版:
function deepest (subMenu, select) {
return [].slice.call (subMenu.querySelectorAll (select)).reduce (
function (deepest, el) {
for (var d = 0, e = el; e !== subMenu; d++, e = e.parentNode);
return d > deepest.d ? {d: d, el: el} : deepest;
}, {d: 0, el: subMenu}).el;
};
用
打电话deepest (subMenu, '.active');
其中第二个参数选择要考虑的元素。
的修改版本上测试过