在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> 
+0

请注意,虽然您已将'class =“parent”'放入您的标记中,但确实没有理由这样做。如下面的答案所示,使用'nearest('li')'查找最近的拥有物品。你甚至不需要'class =“child”',因为你可以做'$('li li')。hover(...);' – Phrogz 2012-02-24 04:37:21

一点都没错— CSS不允许您对DOM树向上遍历,只有向下。如在,你可以选择孩子,但不是父母。

这里有一个方法用jQuery做到这一点:

$("li.child").on("hover", function(){ 
    $(this) 
     .closest("li.parent") 
     .css({ 
      // styling here 
     }); 
}); 

我们做的是与类child选择li元素。我们将hover事件绑定到它并在该事件发生时触发一个函数。该函数找到子类li与类parent最接近的父亲,并且我们更改其CSS。

更多关于on()hereclosest()herecss()here

另外请记住,对于早期版本的jQuery,您可以使用bind()delegate()

编辑:把它改变鼠标悬停鼠标移开:

$("li.child").on("mouseover mouseout", function(){ 
    $(this) 
     .closest("li.parent") 
     .toggleClass("myClass"); 
}); 

而你在这里做什么是你的CSS定义类myClasstoggleClass将添加该类,如果它尚不存在于该元素上并将其删除。这是自我解释。这样,您可以节省几个字节,并使用更受欢迎和推荐的jQuery。

+0

小的澄清:与CSS中相邻的兄弟选择器可以遍历'向下'在源代码中,但在DOM树方面是“横盘”的。 – Phrogz 2012-02-24 04:28:10

使用jQuery的悬停为此。

$(".child").hover(function(){ 
$(".parent").css() //check the jquery css api for the styling options 
}) 
+0

这将选择整个DOM中的所有'.parent'元素。 – Phrogz 2012-02-24 04:28:59

+1

我假设只有一个班级叫他父母从他问什么。答案没有问题,只是过于笼统 – XepterX 2012-02-24 04:33:48

像这样的东西应该工作:

//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获取对父母。

观看演示:http://jsfiddle.net/D8zTE/1/

+1

检查[this](http://api.jquery.com/closest/)了。 – Purag 2012-02-24 04:14:43

+0

的确如此,但我认为他只想从孩子中选择两个级别,而不必关心它的类别。 – gideon 2012-02-26 08:24:07

你可以做这样的事情:

$('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' 
    //}); 
});