如何设置一个跨越特定类的跨度的跨度

时间:2017-02-03 17:43:40

标签: javascript html css

我有一个div,里面有100个跨度,类为s2,另一个带有类s1。这个s1跨度可以在div内的任何位置。我想将css仅应用于s1之后的第一个s2跨度。怎么在css中做到?

<div>
    <span class="s2"></span>
    <span class="s2"></span>
    <span class="s2"></span>
    <span class="s2"></span>
    <span class="s1"></span>
    <span class="s2"></span> <<- i want to style this span
    <span class="s2"></span>
    <span class="s2"></span>
    <span class="s2"></span>
    .
    .
    .
    .
    .
    <span class="s2"></span>
</div>

4 个答案:

答案 0 :(得分:2)

.s1+.s2 {
  /* your styles here */
}
  

元素+元素选择器用于选择放置的元素   紧接在第一个指定元素之后(不在其中)。

http://www.w3schools.com/cssref/sel_element_pluss.asp

答案 1 :(得分:1)

您可以使用adjacent sibling selector

  

这被称为相邻选择器或下一个兄弟选择器。它将仅选择紧跟在前一个指定元素之后的指定元素。

.s1 + .s2 { /* CSS here */ }

&#13;
&#13;
.s1 + .s2 {
  color: red
}
&#13;
<div>
  <span class="s2">1</span>
  <span class="s2">1</span>
  <span class="s2">1</span>
  <span class="s2">1</span>
  <span class="s1">2</span>
  <span class="s2">1</span> 
  <span class="s2">1</span>
  <span class="s2">1</span>
  <span class="s2">1</span>
  <span class="s2">1</span>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

有几种方法:

在CSS中,你可以这样做:

  .s2:nth-child(5) {}       /* get any .s2 that is the 5th child within its parent */
  .s2:nth-last-child(4) {}  /* get any .s2 that is the 4th from last child within its parent */
  .s1 + .s2 {}              /* get any .s2 that immediately follows an .s1 */

在JavaScript中,你可以这样做:

  document.querySelector(".s2:nth-child(5)").style.....;
  document.querySelector(".s2:nth-last-child(4)").style.....;
  document.querySelector(".s1 + .s2").style.....;

这些都假设所有这些元素之间的层次关系是静态的。

详细了解选择器 here

答案 3 :(得分:-1)

您可以使用CSS3运算符

.s1~.s2:nth-​​of-type(1)

http://www.w3schools.com/cssref/sel_gen_sibling.asp