我有一个包含50个条目的表,其中一些条目的类别为“event”或“comment.‘”。下面是表行条目的外观:
事件、注释、事件、注释、事件
我想要做的是分别替换'event‘和'comment’类名的行颜色。目前我所拥有的是:
tr.event:nth-child(odd) {
background-color: #000;
}
tr.comment:nth-child(odd) {
background-color: #000;
}使用这段代码,我得到的输出是:
黑色(事件)、白色(注释)、黑色(事件)、白色(注释)、黑色(注释)、白色(注释)、黑色(事件)
我希望输出是这样的:
黑色(事件)、黑色(注释)、白色(事件)、白色(注释)、黑色(注释)、白色(注释)、黑色(事件)
任何帮助都是最好的!
发布于 2017-06-29 01:57:53
我认为使用纯css是不可能的。
对同样问题的一个非常好的回答可以在这里找到:Can I combine :nth-child() or :nth-of-type() with an arbitrary selector?
我的建议是:为每个奇怪的元素添加一个新类,并相应地设置该元素的样式。
所以你将会有
.comment
.event
.comment.odd
.event.odd
.event
.event.odd
.comment 等
否则,您可以使用js完成此操作。但是额外的类方法应该足够好了。
发布于 2017-06-29 01:59:47
您试图用一个非分层的HTML结构来表示本质上是分层的数据。nth-child指子对象在其父对象中的顺序,而不是在具有某个共享类的所有子对象中的顺序。所以基本上,你不能在CSS中做到这一点。
如果可以的话,试着这样组织HTML:
<div>
<div class="event">
<div class="comment"></div>
</div>
<div class="event">
<div class="comment"></div>
<div class="comment"></div>
<div class="comment"></div>
</div>
<div class="event">
</div>
</div>现在,您可以使用以下命令设置样式
.event:nth-child(odd) { color: white; }
.event:nth-child(even) { color: black; }
.comment:nth-child(odd) { color: white; }
.comment:nth-child(even) { color: black; }由于您似乎希望注释的开头颜色与它所在的活动的颜色相同,因此需要这样做:
.event:nth-child(odd) { color: white; }
.event:nth-child(odd) .comment:nth-child(odd) { color: white; }
.event:nth-child(odd) .comment:nth-child(even) { color: black; }
.event:nth-child(even) { color: black; }
.event:nth-child(even) .comment:nth-child(odd) { color: black; }
.event:nth-child(even) .comment:nth-child(even) { color: white; }上面使用的是div元素。但是,如果您真的想对表执行此操作,可以尝试使用以下HTML,然后使用与上面相同的逻辑:
<table>
<thead><tr><td>Event</td></tr></thead>
<tbody>
<tr><td>Comment</td></tr>
</tbody>
<thead <tr><td>Event</td></tr></thead>
<tbody>
<tr><td>Comment</td></tr>
<tr><td>Comment</td></tr>
<tr><td>Comment</td></tr>
</tbody>
<thead><tr><td>Event</td></tr></thead>
</table>然后写下:
thead:nth-of-type(odd) { color: white; }
tbody:nth-of-type(even) tr:nth-child(odd) { color: white; }
tbody:nth-of-type(odd) tr:nth-child(event) { color: black; }
thead:nth-of-type(even) { color: black; }
tbody:nth-of-type(even) tr:nth-child(odd) { color: black; }
tbody:nth-of-type(odd) tr:nth-child(event) { color: white; }发布于 2017-06-29 02:04:02
使用纯CSS是不可能的,你必须使用jQuery来添加一个类(或者如果你愿意,可以直接添加样式)。
jQuery的索引从0开始,所以它认为是偶数,我们认为是奇数。
我添加了绿色,这样您就可以看到单元格中的内容。
$('table').each(function() {
$('tr.comment:even').addClass('odd');
$('tr.event:even').addClass('odd');
});tr.comment.odd {
background-color: #000;
}
tr.event.odd {
background-color: #000;
}
table {
color: green;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr class="event">
<td>event</td>
</tr>
<tr class="comment">
<td>comment</td>
</tr>
<tr class="event">
<td>event</td>
</tr>
<tr class="comment">
<td>comment</td>
</tr>
<tr class="comment">
<td>comment</td>
</tr>
<tr class="comment">
<td>comment</td>
</tr>
<tr class="event">
<td>event</td>
</tr>
</table>
https://stackoverflow.com/questions/44809321
复制相似问题