评论
如何在uni-app中动态设置列表项的文字颜色,并且重复循环颜色

如何在uni-app中动态设置列表项的文字颜色,并且重复循环颜色

在某个年纪之前,你可以靠透支身体,小聪明和老天给你的运气一直取巧地活着。然而到了某个年纪之后,真正能让你走远的,都是自律,积极和勤奋

需求

这几有遇到一个在uni-app中动态设置列表项的文字颜色,并且无线循环问题

列表要不停循环颜色值,例如说文字1-8条循环颜色之后,第9条又要重新开始循序

前提

列表数组里面有20条数据,

循环颜色数组只有8条

学习

其实核心只有一条,uni-app通过动态计算索引值取余颜色数组的长度

:style="{ color: fontColor[index % fontColor.length] }"

效果

案例

<template>
  <view>
    <!-- 列表 -->
    <view class="lis-flex">
      <block v-for="(item,index) in 20" :key="index">
        <view class="lis-item" v-if="fontColor != ''">
          <view class="lis-img"  :style="{ color: fontColor[index % fontColor.length] }">
            阿
          </view>
          <view class="lis-title">
            阿萨德
          </view>
        </view>
      </block>
    </view>
​
  </view>
</template>
​
<script>
  export default {
    data() {
      return {
​
        fontColor: ["rgb(138, 84, 208)", "rgb(232, 58, 91)",  "rgb(250, 131, 71)", "rgb(65, 64, 125)",
          "rgb(53, 199, 84)", "rgb(73, 120, 240)","rgb(232, 58, 91)","rgb(65, 64, 125)",
        ],
        
      }
    },
    methods: {
      
    }
  }
</script>
​
<style>
  page {
    background-color: #F8F8F8;
  }
​
​
  .lis-flex {
    display: flex;
    /* justify-content: center; */
    padding: 20rpx;
    flex-wrap: wrap;
    background-color: #ffffff;
    border-radius: 20rpx 0;
​
  }
​
  .lis-item {
    width: 30%;
    margin: 10rpx;
    flex-shrink: 0;
    position: relative;
    background-color: rgb(246, 247, 251);
    /* box-shadow: 0 0 5px rgba(0, 0, 0, .08); */
    border-radius: 20rpx;
    overflow: hidden;
  }
​
  .lis-img {
    font-size: 70rpx;
    border-radius: 20rpx;
    margin: 30rpx auto;
    overflow: hidden;
    text-align: center;
  }
​
  .lis-title {
    text-align: center;
    font-size: 30rpx;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
    margin-bottom: 30rpx;
  }
</style>