Html 如何使用 CSS 获取特定数字的孩子?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5664773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get a specific number child using CSS?
提问by Satch3000
I have a table
whose td
s are created dynamically. I know how to get the first and last child but my question is:
我有一个table
,其td
s的动态创建。我知道如何得到第一个和最后一个孩子,但我的问题是:
Is there a way of getting the second or third child using CSS?
有没有办法使用 CSS 获得第二个或第三个孩子?
回答by BoltClock
For modern browsers, use td:nth-child(2)
for the second td
, and td:nth-child(3)
for the third. Remember that these retrieve the second and third td
for every row.
对于现代浏览器,请使用td:nth-child(2)
第二个td
和td:nth-child(3)
第三个。请记住,这些检索td
每一行的第二个和第三个。
If you need compatibility with IE older than version 9, use sibling combinators or JavaScript as suggested by Tim. Also see my answer to this related questionfor an explanation and illustration of his method.
如果您需要与版本 9 之前的 IE 兼容,请使用Tim 建议的兄弟组合器或 JavaScript 。另请参阅我对这个相关问题的回答,以了解他的方法的解释和说明。
回答by Tim
For IE 7 & 8 (and other browsers without CSS3 support not including IE6) you can use the following to get the 2nd and 3rd children:
对于 IE 7 和 8(以及其他不支持 CSS3 的浏览器,不包括 IE6),您可以使用以下内容来获取第二个和第三个孩子:
2nd Child:
第二个孩子:
td:first-child + td
3rd Child:
第三个孩子:
td:first-child + td + td
Then simply add another + td
for each additional child you wish to select.
然后只需+ td
为您希望选择的每个额外孩子添加另一个。
If you want to support IE6 that can be done too! You simply need to use a little javascript (jQuery in this example):
如果你想支持IE6那也可以!你只需要使用一点 javascript(在这个例子中是 jQuery):
$(function() {
$('td:first-child').addClass("firstChild");
$(".table-class tr").each(function() {
$(this).find('td:eq(1)').addClass("secondChild");
$(this).find('td:eq(2)').addClass("thirdChild");
});
});
Then in your css you simply use those class selectors to make whatever changes you like:
然后在您的 css 中,您只需使用这些类选择器来进行您喜欢的任何更改:
table td.firstChild { /*stuff here*/ }
table td.secondChild { /*stuff to apply to second td in each row*/ }