html - CSS 选择器:父类匹配子类
问题描述
我有一个看起来像这样的 html 结构:
<ul class = "one">
<li class = "one">one</li>
<li class = "two">two</li>
</ul>
<ul class = "four">
<li class = "three">three</li>
<li class = "four">four</li>
</ul>
我想创建一个 css 选择器,它选择父类和子类匹配的元素(另请参见我的jsfiddle 示例。到目前为止,我对此非常明确:
.one > .one,
.two > .two
.three > .three,
.four > .four
{
color: red
}
有没有办法不那么明确?像这样的东西:if parent classes match child class
?
解决方案
你不能用纯 CSS 选择父级,伪“:has”只是草稿,现在任何浏览器都不支持它。https://developer.mozilla.org/en-US/docs/Web/CSS/:has
不过用jquery很容易
$(function() {
$("li").each(function(index) {
if ($(this).parent('ul').attr('class') == $(this).attr('class')) {
$(this).css('color', 'red')
}
});
})
推荐阅读
- ruby - 使用 httparty 对 Intercom API 的 POST 调用不起作用,因为“查询正文必须包含查询哈希”
- python - python列表中的变量扩展
- ios - UITableView 中的 Swift Autolayout headerview [已解决]
- javascript - 如何修复现场损坏的滚动条
- android - AAPT:错误:“#ffffff”与可绘制属性 (attr) 引用不兼容
- jestjs - 开玩笑测试后杀死或关闭阿波罗服务器上的 websocket
- node.js - 尝试启动 expo 项目时达到文件观察者数量的系统限制
- javascript - 在事件侦听器中使用对象有什么意义吗?
- c# - C# HttpClient POST 使用带键的表单数据
- perl - find a digit in $_ and add data to $_ in perl