如何选择作为锚元素的直接父元素的<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中工作。

其他回答

您可以使用以下脚本:

*! > 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中工作。

从技术上讲,没有直接的方法可以做到这一点。但是,您可以使用jQuery或JavaScript进行排序。

然而,你也可以这样做。

a.active h1 {color: blue;}
a.active p {color: green;}

jQuery

$("a.active").parents('li').css("property", "value");

如果您想使用jQuery实现这一点,这里是jQuery父选择器的引用。

试试这个。。。

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

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

转到

单击。

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

基于子元素更改父元素当前只能在父元素中有<input>元素时发生。当输入获得焦点时,其对应的父元素可能会使用CSS受到影响。

以下示例将帮助您理解在CSS中使用:focus in。

.外部div{宽度:400px;高度:400px;填充:50px;浮动:左侧}.outer div:聚焦在{背景:红色;}.内部div{宽度:200px;高度:200px;浮动:左侧;背景:黄色;填充:50px;}<div class=“outer div”><div class=“inner div”>我想根据inner-div更改外部div(背景色)类。有可能吗?<input type=“text”placeholder=“Name”/></div></div>