css选择器 nth-child
总述
一:nth-child
1.1 nth-child(n) 父元素下的第n个子元素,n必须大于0,索引都是从1开始。
1.2 nth-child(odd) 父元素下的奇数子元素 等同于 nth-child(2n-1)
1.3 nth-child(even) 父元素下的偶数子元素 同样区分子元素类型 等同于nth-child(2n)
1.4 nth-child(an+b) 公式计算 n可以为0
1.5 first-child 选择父元素下的第一个子元素 如果第一个子元素不是该类型,选择不到 等同于 nth-child(1)
1.6 last-child 选择父元素下的最后一个子元素 如果最后一个子元素不是该类型,选择不到
二:nth-of-type 匹配属于父元素的特定类型的第 N 个子元素的每个元素 忽略不是该类型的元素的存在
注意:要特别注意一下nth-child和nth-of-type的不同,建议自己动手尝试一下。
例子的话,贴一个我自己练习用的。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../../js/jquery-1.8.3.min.js"></script>
<script>
$(function(){
$('.btn1').click(function(){
if($('.btn1').text()=='设置第2个背景色为红色'){
$('div p:nth-child(2)').css("background","crimson");
$('.btn1').text('设置第2个背景色为黑色');
}else{
$('div p:nth-child(2)').css("background","black");
$('.btn1').text('设置第2个背景色为红色');
}
});
// $('.btn2').click(function(){
// $('div p:nth-child(odd)').css("background","blue");
// })
$('.btn2').click(function(){
$('div p:nth-child(2n-1)').css("background","blue");
})
// $('.btn3').click(function(){
// $('div p:nth-child(2n)').css("background","blue");
// })
$('.btn3').click(function(){
$('div p:nth-child(even)').css("background","blue");
})
$('.btn4').click(function(){
$('div p:nth-child(-n+3)').css("background","blue");
})
$('.btn5').click(function(){
$('div p:nth-child(n+0)').css("background","blue");
})
$('.btn6').click(function(){
$('div h1:first-child').css("background","darkmagenta");
})
$('.btn7').click(function(){
$('div p:last-child').css("background","darkmagenta");
})
$('.btn8').click(function(){
$('div p:nth-of-type(1)').css("background","darkmagenta");
})
})
</script>
</head>
<body>
<div>
<h1>愿你万事顺意,迎难而上。</h1>
<p>祝你前程似锦</p>
<p>祝你前程似锦</p>
<p>祝你前程似锦</p>
<p>祝你前程似锦</p>
<p>祝你前程似锦</p>
</div>
<div class="content">
<button class="btn1">设置第2个背景色为红色</button>
<button class="btn2">设置奇数背景色为蓝色</button>
<button class="btn3">设置奇数背景色为蓝色</button>
<button class="btn4">设置前3个背景色为蓝色</button>
<button class="btn5">设置所有背景色为蓝色</button>
<button class="btn6">找到第一个元素,设置颜色为紫色</button>
<button class="btn7">找到最后一个元素,设置颜色为紫色</button>
<button class="btn8">找到第一个元素,设置颜色为紫色(直到找到)</button>
</div>
</body>
</html>