在CSS中选择子级的父级 [英] Selecting Parent of a Child in CSS

查看:821
本文介绍了在CSS中选择子级的父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用下面的代码,我想能够将CSS样式应用到列表中的父 li class =parent项。但只有当用户将鼠标悬停在该特定父项的 li class =child项目上时。

With the following code below I want to be able to apply a CSS style to the parent li class="parent" item in the list. But only when the user is hovering over the child li class="child" items for that particular parent.

这是我的理解,这将不可能使用CSS,但任何人都知道一个潜在的Javascript解决方案(理想情况下使用jQuery,因为我们已经在我们的网站上使用这个库)

It's my understanding that this won't be possible using just CSS, but does anyone know of a potential Javascript solution (ideally using jQuery, as we're already using this library on our website)

谢谢!

<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树,只向下。

You heard right—CSS doesn't allow you to traverse upward on the DOM tree, only downward. As in, you can select children, but not parents.

这里有一个使用jQuery的方法:

Here's one method to do it with jQuery:

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

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

What we do is select the li element with the class child. We bind the hover event to it and fire a function when that event occurs. The function finds the closest parent of the child li with the class parent, and we change its CSS.

更多 on() 此处 closest() 此处 css() 此处 a>。

More on on() here, closest() here, and css() here.

请记住,对于早期版本的jQuery,可以使用 bind() code> delegate()。

Also keep in mind that for earlier versions of jQuery, you can use bind() or delegate().

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

To have it change on mouseover and mouseout:

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

你在这里做的是定义类 myClass toggleClass 添加类,如果它在元素上不存在,否则删除它。这是自我解释。这样,你保存了几个字节,并使用更喜欢和推荐的jQuery。

And what you do here is define the class myClass in your CSS. toggleClass adds the class if it doesn't already exist on the element and removes it otherwise. It's self explanatory. This way, you save a few bytes and use more preferred and recommended jQuery.

这篇关于在CSS中选择子级的父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆