關於nth-child選不到想要元素的問題

慣例先貼問題代碼:

 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			.item:nth-child(2){
				background-color: yellow;
			}
			.item:nth-child(1){
				background-color: red;
			}
		</style>
	</head>
	<body>
		<!--<div id="stage">
			<div class="item"></div>
		</div>-->
		<table id="stage" border="" cellspacing="" cellpadding="">
			<tr><th>Header</th></tr>
			<tr class="item"><td>Data</td></tr>
		</table>
	</body>
	<script type="text/javascript">
		var stage=document.getElementById("stage");
		var itemlist=document.getElementsByClassName("item");
		stage.appendChild(itemlist[0].cloneNode(true));
		stage.appendChild(itemlist[0].cloneNode(true));
		stage.appendChild(itemlist[0].cloneNode(true));
	</script>
</html>

運行結果:

問題:

第一個元素沒有選到,第二個元素選了兩個

 

解決方案:

[element]:nth-child(n)

這個僞類選擇器的意思並不是父元素的第n個element元素(如果想這麼做的話要使用nth-of-type)

而是選擇屬於父元素的第n個子元素且爲element的元素

也就是說先找所有父元素的第n個子元素,然後再找其中爲element的元素

由於文檔中身爲第一個子元素的是<tr><th>Header</th></tr>

而這個元素並不是item類的

所以.item:nth-child(1)並沒有選到任何一個元素

但是爲什麼.item:nth-child(2)選擇了兩個元素呢?

讓我們來先看看element:

當使用table標籤沒有寫tbody的時候,網頁會自動生成tbody元素

所以.item:nth-child(2)一開始選擇到了父元素是<tbody>中的第二個元素和父元素是<table>的第二個元素(<tbody>是第一個),

然後這兩個元素都是item類的,所以都被選擇到了

 

 

 

 

 

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