如何选择作为锚元素的直接父元素的<li>元素?

例如,我的CSS应该是这样的:

li < a.active {
    property: value;
}

很显然,JavaScript有很多方法可以做到这一点,但我希望有某种变通方法可以在CSS Level 2中使用。

我正在尝试设置样式的菜单被CMS弹出,因此我无法将活动元素移动到<li>元素。。。(除非我对菜单创建模块进行主题化,否则我不想这样做)。


当前回答

我认为你不能只在CSS中选择父级。

但由于您似乎已经有一个.active类,所以将该类移动到li(而不是a)会更容易。这样,您只能通过CSS访问li和a。

其他回答

试试这个。。。

此解决方案使用无Javascript的简单CSS2规则,适用于所有浏览器,无论新旧浏览器。单击时,子锚点标记将激活其活动的伪类事件。然后,它简单地隐藏自己,允许活动事件向上冒泡到父li标签,然后父li标签重新设计自己的样式,并以新样式再次显示其锚定子对象。子对象已设置父对象的样式。

使用您的示例:

<ul>
    <li class="listitem">
        <a class="link" href="#">This is a Link</a>
    </li>
</ul>

现在,将这些样式应用于a上的活动伪类,以在单击链接时重新设置父li标记的样式:

a.link {
    display: inline-block;
    color: white;
    background-color: green;
    text-decoration: none;
    padding: 5px;
}

li.listitem {
    display: inline-block;
    margin: 0;
    padding: 0;
    background-color: transparent;
}

/* When this 'active' pseudo-class event below fires on click, it hides itself,
triggering the active event again on its parent which applies new styles to itself and its child. */

a.link:active {
    display: none;
}

.listitem:active {
    background-color: blue;
}

.listitem:active a.link {
    display: inline-block;
    background-color: transparent;
}

单击时,您应该会看到带有绿色背景的链接现在变为列表项的蓝色背景。

转到

单击。

我知道OP正在寻找CSS解决方案,但使用jQuery很容易实现。在我的例子中,我需要为包含在子<li>中的<span>标记找到<ul>父标记。jQuery具有:has选择器,因此可以通过它包含的子项来标识父项:

$("ul:has(#someId)")

将选择具有id为someId的子元素的ul元素。或者,为了回答最初的问题,应该使用以下方法(未经测试):

$("li:has(.active)")

只是一个水平菜单的想法。。。

HTML的一部分

<div class='list'>
  <div class='item'>
    <a>Link</a>
  </div>
  <div class='parent-background'></div>
  <!-- submenu takes this place -->
</div>

CSS的一部分

/* Hide parent backgrounds... */
.parent-background {
  display: none; }

/* ... and show it when hover on children */
.item:hover + .parent-background {
  display: block;
  position: absolute;
  z-index: 10;
  top: 0;
  width: 100%; }

更新的演示和其余代码

另一个示例是如何将其用于文本输入-选择父字段集

据我所知,CSS 2中没有。CSS 3具有更强大的选择器,但并不是在所有浏览器中都一致实现。即使有了改进的选择器,我也不相信它能完全实现您在示例中指定的功能。

否,不能仅在CSS中选择父级。

但由于您似乎已经有一个.active类,所以将该类移动到li(而不是a)会更容易。这样,您只能通过CSS访问li和a。