在CSS中选择一个孩子的父亲
在下面的代码中,我希望能够将CSS样式应用于父列表li class="parent"
项目。但是,只有当用户在该子女的子项li class="child"
上悬停时才会生效。在CSS中选择一个孩子的父亲
这是我的理解是,这将是不可能只使用CSS,但没有人知道一个潜在的JavaScript解决方案的(理想情况下使用jQuery,因为我们已经在使用我们的网站上这个库)
谢谢!
<ul>
<li class="parent"><a href="URL" >Main Link</a>
<ul class="sub-menu">
<li class="child"><a href="URL" >Link</a></li>
</ul>
</li>
</ul>
一点都没错— CSS不允许您对DOM树向上遍历,只有向下。如在,你可以选择孩子,但不是父母。
这里有一个方法用jQuery做到这一点:
$("li.child").on("hover", function(){
$(this)
.closest("li.parent")
.css({
// styling here
});
});
我们做的是与类child
选择li
元素。我们将hover
事件绑定到它并在该事件发生时触发一个函数。该函数找到子类li
与类parent
最接近的父亲,并且我们更改其CSS。
更多关于on()
here,closest()
here和css()
here。
另外请记住,对于早期版本的jQuery,您可以使用bind()
或delegate()
。
编辑:把它改变鼠标悬停和鼠标移开:
$("li.child").on("mouseover mouseout", function(){
$(this)
.closest("li.parent")
.toggleClass("myClass");
});
而你在这里做什么是你的CSS定义类myClass
。 toggleClass
将添加该类,如果它尚不存在于该元素上并将其删除。这是自我解释。这样,您可以节省几个字节,并使用更受欢迎和推荐的jQuery。
小的澄清:与CSS中相邻的兄弟选择器可以遍历'向下'在源代码中,但在DOM树方面是“横盘”的。 – Phrogz 2012-02-24 04:28:10
像这样的东西应该工作:
//The hover method takes two functions, one it does on mouseover
//and the other executes on mouseout
$(".child").hover(
function(){//get the parent -> then get its parent (the li)
$(this).parent().parent().addClass("parent");//add the class to it
},
function(){//this executes on mouseout
$(this).parent().parent().removeClass("parent");
}//remove the class..
);
您可以使用.parent
类作为标记和使用jQuery的class selector或者你可以使用一个variety of other selectors获取对父母。
你可以做这样的事情:
$('li.child').hover(function() {
$(this).closest('.parent').addClass('red');
}, function() {
$(this).closest('.parent').removeClass('red');
});
工作例如:
$("li.child").hover(function() {
$(this).parents('li.parent').addClass('parentHoverClass');
//Alternatively, you could apply inline styles to the <li> like this:
//$(this).parents('li.parent').css({
// 'display': 'block',
// 'color': '#FF00FF',
// 'text-decoration': 'underline'
//});
}, function() {
$(this).parents('li.parent').removeClass('parentHoverClass');
//Or, you could reset inline styles to the <li> like this:
//$(this).parents('li.parent').css({
// 'display': 'inline',
// 'color': '#00FF00',
// 'text-decoration': 'none'
//});
});
请注意,虽然您已将'class =“parent”'放入您的标记中,但确实没有理由这样做。如下面的答案所示,使用'nearest('li')'查找最近的拥有物品。你甚至不需要'class =“child”',因为你可以做'$('li li')。hover(...);' – Phrogz 2012-02-24 04:37:21