目录

一、问题

二、原因及解决方法

三、总结


 

tiips:如嫌繁琐,直接移步总结即可!

一、问题

1.想使用伪类:last-child给 for循环出来的最后一个元素单独添加样式。但是发现无论怎么写都没有添加上去。

2.真是奇怪呀,明明写的没有问题呀,但是检查元素的时候确实看不到样式。

二、原因及解决方法

1.预期效果:第一个元素 红色;最后一个元素绿色

    html如下,效果如下图2-1所示

<template>
    <div class="test-area">
      <div
        class="test-box"
        v-for="(firstItem, firstKey) of firstData"
        :key="firstKey"
      >
        {{ firstItem.label }}
      </div>
      <div class="other-area"></div>
    </div>
</template>
<script lang="scss" scoped>
  .test-area {
    color: #333;
    .test-box {
      &:last-child {
        color: green;
      }
      &:first-child {
        color: red;
      }
    }
  }
</script>

a4c76f84b8f9a4138f66cd83eefd8b7c.png

图 2-1

2.为什么 最后一个元素不是绿色呢? 为什么 :first-child可以,:last-child不生效呢

检查元素,发现第一个元素添加了 :frist-child伪类样式,最后一个元素却没有。如图2-2所示

4e3e56e8e57737f05521e073f709a6b7.png

图 2-2

3.删除        <div class="other-area"></div>   竟然好了

dce152882b25a9e81ac51f2db1b9ca30.png

图 2-3

4.把   <div class="other-area"></div> 放在第一个test-box前面,:first-child竟然失效了!!!!!!

56d779ca1e088450ee50caf21a282dda.png

图 2-4

5.原因::first-child只在被选中的第一个元素前面没有其他元素才生效;

 :last-child只在被选中的最后一个元素后面没有其他元素时才生效

上面的代码中.test-box:last-child后面还有同级的元素 other-area,所以不生效

6.解决方法:在被循环的test-box外面添加一个父盒子如图2-5所示

代码如下:

<template>
    <div class="test-area">
      <div class="box-area">
        <div
          class="test-box"
          v-for="(firstItem, firstKey) of firstData"
          :key="firstKey"
        >
          {{ firstItem.label }}
        </div>
      </div>
      <div class="other-area"></div>
    </div></template>
<script lang="scss" scoped>
  .test-area {
    color: #333;
    .test-box {
      &:last-child {
        color: green;
      }
      &:first-child {
        color: red;
      }
    }
  }
</script>

 

c0196b7bc27c73a145e72a0f5b3da831.png

 

三、总结

1. :first-child,:last-child生效的前提

:first-child只在被选中的第一个元素前面没有其他元素才生效;

 :last-child只在被选中的最后一个元素后面没有其他元素时才生效

 

/*

希望对你有帮助!

如有错误,欢迎指正,非常感谢!

*/

 

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐