实现数组三个样式一轮换

需求:一个list,第一个是一种背景图样式,第二个是一种背景图样式,第三个又是一种样式,然后第四个是第一个样式,以此类推

实现效果:

 

js+css实现代码:

<template>
  <div class="page" v-if="list && list.length > 0">
    <div
      class="item"
      v-for="(item, index) in list"
      :key="item.id"
      :class="cardColors[index].backgourund"
    >
      {{ item.name }}
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      list: [
        { name: '第一个item', id: 2 },
        { name: '第二个item', id: 3 },
        { name: '第三个item', id: 4 },
        { name: '第四个item', id: 5 },
        { name: '第五个item', id: 6 },
        { name: '第六个item', id: 7 },
        { name: '第七个item', id: 8 },
        { name: '第八个item', id: 9 },
        { name: '第九个item', id: 10 },
        { name: '第十个item', id: 11 },
        { name: '第十一个item', id: 12 },
        { name: '第十个item', id: 13 },
        { name: '第十一个item', id: 14 },
      ],
      cardColors: [
        {
          backgourund: 'backgourund',
        },
        {
          backgourund: 'backgourund1',
        },
        {
          backgourund: 'backgourund2',
        },
      ],
    }
  },
  mounted() {
    //这段代码可写入接口请求里面
    setTimeout(() => {
      if (this.list.length > this.cardColors.length) {
        let number = Math.ceil(this.list.length / 3)
        for (let i = 0; i < number; i++) {
          this.cardColors = this.cardColors.concat(this.cardColors)
        }
      }
    }, 100)
  },
  methods: {},
}
</script>

<style lang="less" scoped>
.page {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 15px 15px 0;
  .item {
    background-color: yellowgreen;
    width: 100%;
    height: 100px;
    border-radius: 10px;
    margin-bottom: 15px;
    color: #fff;
    text-align: center;
    line-height: 100px;
  }
  .backgourund {
    background-color: skyblue !important;
  }
  .backgourund1 {
    background-color: pink !important;
  }
  .backgourund2 {
    background-color: green !important;
  }
}
</style>

纯css代码实现:

.page {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 15px;
  .item {
    background-color: yellowgreen;
    width: 100%;
    height: 100px;
    border-radius: 10px;
    margin-bottom: 15px;
    color: #fff;
    text-align: center;
    line-height: 100px;
    /* 第1个和第4个 */
    &:nth-child(3n + 1) {
      /* 样式1 */
      background-color: skyblue;
    }

    /* 第2个和第5个 */
    &:nth-child(3n + 2) {
      /* 样式2 */
      background-color: pink;
    }

    /* 第3个和第6个 */
    &:nth-child(3n + 3) {
      /* 样式3 */
      background-color: green;
    }
  }
}

 

 

 

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值