在CSS中选择子级的父级

时间:2012-02-24 03:51:30

标签: jquery html css parent

使用下面的代码,我希望能够将CSS样式应用于列表中的父li class="parent"项。但仅当用户将鼠标悬停在该特定父级的子li class="child"项上时。

我的理解是,这不可能只使用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>

5 个答案:

答案 0 :(得分:2)

你听说过 - CSS不允许你在DOM树上向上遍历,只是向下。如同,您可以选择孩子,但不能选择父母。

以下是使用jQuery执行此操作的一种方法:

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

我们所做的是选择li类,其中包含child类。我们将hover事件绑定到它并在该事件发生时触发函数。该函数使用类li查找子parent的最近父项,并更改其CSS。

有关on() hereclosest() herecss() here的更多信息。

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

编辑:要在鼠标悬停时更改 mouseout:

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

你在这里做的是在CSS中定义类myClasstoggleClass如果该元素尚不存在,则添加该类,否则将其删除。这是自我解释的。这样,您可以节省几个字节并使用更多首选和推荐的jQuery。

答案 1 :(得分:2)

您可以这样做:

$('li.child').hover(function() {
   $(this).closest('.parent').addClass('red');
}, function() {
   $(this).closest('.parent').removeClass('red');    
});

工作示例:

答案 2 :(得分:0)

这样的事情应该有效:

//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/

答案 3 :(得分:0)

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

答案 4 :(得分:-1)

使用jquery悬停为此。

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