前景

一段HTML代码,我需要让第一个类名为content的div背景设置为红色的

  1. js代码
1
2
3
4
<div class="header">1</div>
<div class="content">2</div>
<div class="header">3</div>
<div class="content">4</div>
  1. style样式
1
2
3
4
5
6
7
<style>
div{
width: 100px;
height: 100px;
border: 1px solid red;
}
</style>

一开始想到的

  1. 要选第一个类名为content,当然是nth-of-type了,因为我只想要让拥有content类的div容器被选择
1
2
3
4
5
6
7
//错误的选择器代码
<style>
.content:nth-of-type(1){
background-color: red;
}
</style>

  1. 结果如下

为什么没有用?

  1. :nth-of-type当中没有指定标签,那么就会查找第一个匹配的,同级别下所对应的所有元素标签(后面有具体解释和示例)
  2. :nth-of-type针对的是标签选择器,也就说你用类和nth-of-type结合使用是不恰当的,如果要使用,记得先用类名筛选,再用标签使用nth-of-type选择器
1
2
3
4
//也就是这种,先用类名筛选,再用标签使用nth-of-type选择器
.one p:nth-of-type(2){
xxxxxx
}

分析设置代码的,浏览器做了什么

1
2
3
4
5
6
   //也就是这段js代码
<style>
.content:nth-of-type(1){
background-color: red;
}
</style>
1
2
3
4
5
<!--js代码对应的html代码-->
<div class="header">1</div>
<div class="content">2</div>
<div class="header">3</div>
<div class="content">4</div>

浏览器做了什么示意图

再来举个例子

  1. 首先,由于我们没有书写具体要在哪一个标签,那么浏览器就会全局查找拥有这个类的标签,并且把这个类下同级别的所有标签加入到待查列表

  2. .content:nth-of-type(2) 例子

  3. .content:nth-of-type(1)例子