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

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

li < a.active {
    property: value;
}

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

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


当前回答

您可以使用以下脚本:

*! > input[type=text] { background: #000; }

这将选择文本输入的任何父级。但等等,还有很多。如果需要,可以选择指定的父级:

.input-wrap! > input[type=text] { background: #000; }

或在它处于活动状态时选择它:

.input-wrap! > input[type=text]:focus { background: #000; }

查看此HTML:

<div class="input-wrap">
    <input type="text" class="Name"/>
    <span class="help hide">Your name sir</span>
</div>

当输入激活时,您可以选择该span.help并显示:

.input-wrap! .help > input[type=text]:focus { display: block; }

还有更多的功能;只需查看插件的文档即可。

顺便说一下,它在Internet Explorer中工作。

其他回答

在CSS 2中没有办法做到这一点。您可以将类添加到li中并引用a:

li.active > a {
    property: value;
}

CSS选择器“General Sibling Combinator”可能用于您想要的用途:

E ~ F {
    property: value;
}

这匹配前面有E元素的任何F元素。

没有css(因此在css预处理器中)父选择器,因为“css工作组先前拒绝父选择器建议的主要原因与浏览器性能和增量渲染问题有关。”

有一个插件可以扩展CSS,以包含一些非标准功能,这些功能在设计网站时非常有用。这叫做EQCSS。

EQCSS添加的内容之一是父选择器。它适用于所有浏览器,Internet Explorer 8及更高版本。格式如下:

@element 'a.active' {
  $parent {
    background: red;
  }
}

因此,我们在每个元素a.active上打开了一个元素查询,对于该查询中的样式,类似$parent这样的东西是有意义的,因为有一个参考点。浏览器可以找到父节点,因为它与JavaScript中的parentNode非常相似。

这里有一个$parent的演示和另一个在Internet Explorer 8中运行的$parent演示,以及一个屏幕截图,以防您没有Internet Explorer 8进行测试。

EQCSS还包括元选择器:$prev用于所选元素之前的元素,$this仅用于与元素查询匹配的元素,等等。

试试这个。。。

此解决方案使用无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;
}

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

转到

单击。