CSS伪类选择器 ——:last-child、:nth-last-child(n)、:nth-last-of-type(n)
在系统的学习前端知识前,一直是JQuery的忠实用户,很大程度上是由于它能够很方便的获取Element对象,通过它强大的选择器 —— 《JQuery选择器》,让我们成功远离原生JS获取Element对象的苦恼和鸡肋:
- document.getElementsByClassName()
- document.getElementById()
- document.getElementsByName()
- document.getElementsByTagName()
随着知识积累,我了解到了document.querySelector(),也是JS的原生选择器,从此爱上了JS不可自拔。
querySelector() 方法返回文档中匹配指定 CSS 选择器的一个元素。
这里我们看出,querySelector()
实际上是通过《CSS选择器》产生作用的,虽然JQuery选择器
也学习了这一点,但是CSS选择器
与JQuery选择器
还是有差别之处的,我们有必要系统的去学习一下。
CSS选择器中的伪类选择器,是我们不常用,但却往往事半功倍的选择器方式。其中的有某些伪类,相信大多数人都在用,但是却没有正确理解,包括很多职业Web前端。其中有:
:first-child、:first-of-type、:last-child、:last-of-type、:nth-child(n)、:nth-last-child(n)、:nth-last-of-type(n)、:nth-of-type(n)、:only-of-type、:only-child
真正理解这些伪类,我们必需要理解:
-
-child(n)
与-of-type(n)
的区别?-child(n)
:先找到指定元素的第n个同级元素(可以不同类型),再判断找到的元素是否与指定元素相同类型;-of-type(n)
:直接找与指定元素同级的第n个同类型元素; -
fist
与last
的区别?fist
:正着数;last
:倒着数;
这里我们以:nth-last-child(n)、:nth-last-of-type(n)为例,带着上面的结论测试下面的代码,就很容易明白了。
代码1:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<style>
.c > p:nth-last-child(1)
{
background:#ff0000;
}
</style>
</head>
<body>
<div class="c">
<div class="b">
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
</div>
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
</div>
<p><b>注意:</b> Internet Explorer 8 以及更早版本的浏览器不支持:nth-last-child()选择器.</p>
</body>
</html>
运行结果:
代码2:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<style>
.c > p:nth-last-child(1)
{
background:#ff0000;
}
</style>
</head>
<body>
<div class="c">
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
<div class="b">
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
</div>
</div>
<p><b>注意:</b> Internet Explorer 8 以及更早版本的浏览器不支持:nth-last-child()选择器.</p>
</body>
</html>
运行结果:
代码3:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<style>
.c > p:nth-last-of-type(1)
{
background:#ff0000;
}
</style>
</head>
<body>
<div class="c">
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
<div class="b">
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
</div>
</div>
<p><b>注意:</b> Internet Explorer 8 以及更早版本的浏览器不支持:nth-last-child()选择器.</p>
</body>
</html>
运行结果: