【问题标题】:How to style a span which is just after another span with a particular class如何设置一个跨度的样式,该跨度紧随特定类的另一个跨度之后
【发布时间】:2017-02-03 17:43:39
【问题描述】:

我有一个 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>

【问题讨论】:

标签: javascript html css


【解决方案1】:
.s1+.s2 {
  /* your styles here */
}

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

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

【讨论】:

    【解决方案2】:

    您可以使用adjacent sibling selector

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

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

    .s1 + .s2 {
      color: red
    }
    <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>

    【讨论】:

      【解决方案3】:

      你可以使用 CSS3 运算符

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

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

      【讨论】:

      • 这也选择了.s1之后的all .s2元素。该问题询问如何选择下一个.s2 元素。
      • 尝试在 s2 之后添加 :nth-of-type(1)
      【解决方案4】:

      有几种方法:

      在 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

      【讨论】:

      • 而且你甚至不需要使用 JavaScript;这些都是 CSS 中的有效选择器,这是 OP 要求的......
      • 是的,但问题被标记为“JavaScript”,所以我提供了一个涵盖两者的答案。
      猜你喜欢
      • 2021-12-30
      • 2020-01-30
      • 2022-12-05
      • 1970-01-01
      • 2019-07-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-29
      • 1970-01-01
      相关资源
      最近更新 更多