使用vue抽象成一个组件
<template> <div class="star"> <span v-for="itemClass in itemClasses" :class="itemClass" class="star-item"></span> </div> </template> <script> const LENGTH = 5 const CLS_ON = 'on' // 亮 const CLS_HALF = 'half' // 半星星 const CLS_OFF = 'off' // 不亮 export default { props: { score: { type: Number } }, computed: { itemClasses () { let result = [] // 向下取整数 let score = Math.floor(this.score) / 2 let starOn = Math.floor(score) let starHalf = (score - starOn) === 0 ? 0 : 1 //整除的情况(整数部分全部点亮) for (let i = 0; i < starOn; i++) { result.push(CLS_ON) } //是否有余数 if (starHalf === 1) { result.push(CLS_HALF) } //剩余的部分全部不亮 while (result.length < LENGTH) { result.push(CLS_OFF) } return result } } } </script> <style> .star-item { display: inline-block; height: 14px; width: 14px; background-size: 10px 10px; } .on { background-image: url(star36_on@2x.png); background-repeat: no-repeat; } .half { background-image: url(star36_half@2x.png); background-repeat: no-repeat; } .off { background-image: url(star36_off@2x.png); background-repeat: no-repeat; } </style>
使用:
<!--score是等级分数 通过props传递参数--> <star :score="8"></star>
即可更加分数的大小来确定星星的等级