美文网首页
根据评分(数字)去设置五星的全满与半满

根据评分(数字)去设置五星的全满与半满

作者: 我是何宝荣呀 | 来源:发表于2020-01-03 16:42 被阅读0次
// 定义星星的最大长度
const LENGHT = 5
// 星星对应的class
const CLS_ON = 'fa-star'
const CLS_HALF = 'fa-star-half-empty'
// 填充
const CLS_OFF = 'fa-star-o'
 //4.8 四个全星 一个半星
      // 装星星
      let result = []

      // 对分数进行处理,向下取0.5倍数 4.8=>4 ----> 4.8*2=9.6=>9  /2 =>4.5  四个全星 一个半星
      let score = Math.floor(this.ratingData * 2) / 2
      //控制半星 小数对1取余的话 会有小数点
      let hasDecimal = score % 1 !== 0
      // 控制全星
      let interger = Math.floor(score)

      // 放入数组
      for (let i = 0; i < interger; i++) {
        // 全星
        result.push(CLS_ON)
      }

      if (hasDecimal) {
        // 半星
        result.push(CLS_HALF)
      }
      while (result.length < LENGHT) {
        // 补齐
        result.push(CLS_OFF)
      }

而后,再去遍历数组,根据数组的类名可以知道是全满的星星还是半满的星星

demo

<template>
  <div class="Rating_gray">
    <div class="Rating-gray_content">
      <i
        v-for="(item, index) in rating"
        :key="index"
        :class="'fa ' + item"
      ></i>
    </div>
  </div>
</template>
<script>
// 定义星星的最大长度
const LENGHT = 5
// 星星对应的class
const CLS_ON = 'fa-star'
const CLS_HALF = 'fa-star-half-empty'
// 填充
const CLS_OFF = 'fa-star-o'
export default {
  name: 'rating',
  props: {
    ratingData: Number
  },
  computed: {
    rating() {
      //4.8 四个全星 一个半星
      // 装星星
      let result = []

      // 对分数进行处理,向下取0.5倍数 4.8=>4 ----> 4.8*2=9.6=>9  /2 =>4.5  四个全星 一个半星
      let score = Math.floor(this.ratingData * 2) / 2
      //控制半星 小数对1取余的话 会有小数点
      let hasDecimal = score % 1 !== 0
      // 控制全星
      let interger = Math.floor(score)

      // 放入数组
      for (let i = 0; i < interger; i++) {
        // 全星
        result.push(CLS_ON)
      }

      if (hasDecimal) {
        // 半星
        result.push(CLS_HALF)
      }
      while (result.length < LENGHT) {
        // 补齐
        result.push(CLS_OFF)
      }
      return result
    }
  }
}
</script>
<style lang="scss" scoped>
.Rating_gray {
  position: relative;
  overflow: hidden;
  display: inline-block;
  vertical-align: middle;
  margin-right: 0.106667rem;
  margin-right: 1.066667vw;
  .Rating-gray_content {
    display: -webkit-flex;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    > i {
      color: #ffe339;
    }
  }
}
</style>

相关文章

网友评论

      本文标题:根据评分(数字)去设置五星的全满与半满

      本文链接:https://www.haomeiwen.com/subject/ehemoctx.html