CSS偽類選擇器 ——:last-child、:nth-last-child(n)、:nth-last-of-type(n)
阿新 • • 發佈:2018-12-29
在系統的學習前端知識前,一直是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)
真正理解這些偽類,我們必需要理解:
-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>
執行結果: