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個同類型元素;
  • fistlast的區別?
    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>

運行結果:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章