活跃孩子的父母的复杂CSS选择器
有没有一种方法可以根据类中子元素的类来选择父元素?与我相关的示例与http://drupal.org的漂亮菜单插件的HTML输出有关。输出呈现如下:
<ul class="menu"> <li> <a class="active">Active Page</a> </li> <li> <a>Some Other Page</a> </li> </ul>
我的问题是,是否可以将样式应用于包含带有活动类的锚点的列表项。显然,我希望将列表项标记为活动状态,但我无法控制所生成的代码。我可以使用javascript执行此类操作(想到的是JQuery),但是我想知道是否可以使用CSS选择器来执行此操作。
为了清楚起见,我想将样式应用于列表项,而不是锚点。
解决方案
回答
不幸的是,CSS无法做到这一点。
使用JavaScript并不是很困难:
// JavaScript code: document.getElementsByClassName("active")[0].parentNode; // jQuery code: $('.active').parent().get(0); // This would be the <a>'s parent <li>.
回答
根据维基百科:
Selectors are unable to ascend CSS offers no way to select a parent or ancestor of element that satisfies certain criteria. A more advanced selector scheme (such as XPath) would enable more sophisticated stylesheets. However, the major reasons for the CSS Working Group rejecting proposals for parent selectors are related to browser performance and incremental rendering issues.
对于将来搜索SO的任何人,也可以将其称为祖先选择器。
更新:
Selectors Level 4 Spec允许我们选择主题的哪一部分:
The subject of the selector can be explicitly identified by prepending a dollar sign ($) to one of the compound selectors in a selector. Although the element structure that the selector represents is the same with or without the dollar sign, indicating the subject in this way can change which compound selector represents the subject in that structure. Example 1: For example, the following selector represents a list item LI unique child of an ordered list OL: OL > LI:only-child However the following one represents an ordered list OL having a unique child, that child being a LI: $OL > LI:only-child The structures represented by these two selectors are the same, but the subjects of the selectors are not.
尽管此功能在任何浏览器中均不可用(当前为2011年11月),但在jQuery中不可用。
回答
我对Drupal也有同样的问题。考虑到CSS的局限性,使此工作正常进行的方法是在生成菜单HTML时将" active"类添加到父元素中。在http://drupal.org/node/219804上对此进行了很好的讨论,其主要结果是该功能已集成到nicemenus模块的6.x-2.x版本中。由于它仍在开发中,因此我已将修补程序反向移植到http://drupal.org/node/465738上的6.x-1.3,以便可以继续使用该模块的生产就绪版本。
回答
再次晚了聚会,但值得的是,使用jQuery可能会更简洁一些。在我的情况下,我需要为子元素<li>中包含的<span>标签找到<ul>
父标签。 jQuery具有:has
选择器,因此可以通过它包含的子对象来识别父对象(根据@Afrowave的注释参考:https://api.jquery.com/has-selector/更新):
$("ul").has("#someId")
将选择具有ID为someId的子元素的ul
元素。或者为回答原始问题,应使用以下方法解决问题(未测试):
$("li").has(".active")