如何在元素列表中选择某个元素?我有以下几点:
<div class="myclass">my text1</div>
<!-- some other code follows -->
<div>
<p>stuff</p>
</div>
<div>
<p>more stuff</p>
</div>
<p>
<span>Hello World</span>
</p>
<div class="myclass">my text2</div>
<!-- some other code follows -->
<div>
<p>stuff</p>
</div>
<p>
<span>Hello World</span>
</p>
<input type=""/>
<div class="myclass">my text3</div>
<!-- some other code follows -->
<div>
<p>stuff</p>
</div>
<footer>The end</footer>
显然,我有适用于所有人的CSS类div.myclass {doing things}
,但我也希望能够像这样选择类.myclass
的第一个、第二个或第三个div,,而不管它们在标记中的什么位置:
div.myclass:first {color:#000;}
div.myclass:second {color:#FFF;}
div.myclass:third {color:#006;}
几乎类似于我当前使用的jQuery索引选择.eq( index )
,但我需要一个无脚本的替代方案。
具体地说,我正在寻找伪选择器,而不是像添加另一个类或使用I这样的东西。
发布于 2011-08-28 17:56:16
在发布这个问题到今天,您可能最终意识到了这一点,但是选择器的本质使得在层次结构上不相关的HTML元素中导航是不可能的。
或者,简单地说,既然你在评论中说
没有统一的父容器
..。如果不像其他答案所示那样以某种方式修改标记,那么仅使用选择器是不可能的。
您必须使用jQuery .eq()
解决方案。
发布于 2012-12-15 10:35:46
使用第n个子项(项目编号) EX
<div class="parent_class">
<div class="myclass">my text1</div>
some other code+containers...
<div class="myclass">my text2</div>
some other code+containers...
<div class="myclass">my text3</div>
some other code+containers...
</div>
.parent_class:nth-child(1) { };
.parent_class:nth-child(2) { };
.parent_class:nth-child(3) { };
或
:nth-of-type(项目编号)与您的代码相同
.myclass:nth-of-type(1) { };
.myclass:nth-of-type(2) { };
.myclass:nth-of-type(3) { };
发布于 2011-10-29 09:13:02
是的,你可以做到。例如,要设置组成表中不同列的td标签的样式,可以执行以下操作:
table.myClass tr > td:first-child /* First column */
{
/* some style here */
}
table.myClass tr > td:first-child+td /* Second column */
{
/* some style here */
}
table.myClass tr > td:first-child+td+td /* Third column */
{
/* some style here */
}
https://stackoverflow.com/questions/2751127
复制相似问题