css实现五星好评样式

五星好评的样式,很多地方都有简单实现,比如设置1星,2星,3星,4星,5星,这个没什么好说的,但是我有强迫症,我要是想看看4.5星的效果呢?就是有半颗星高亮。该如何实现呢?

我的想法是第一层做个默认没有星级的展示底图,然后把想要显示的五星级覆盖底层,然后设置覆盖层的宽度百分比。经过验证,这个思路是可以的。如下所示,

页面结构:

html 复制代码
<view class="star-wrap">
  <view class="star-gray">
    <image class="icon-star" src="../icons/icon-grade-gray.png"></image>
    <image class="icon-star" src="../icons/icon-grade-gray.png"></image>
    <image class="icon-star" src="../icons/icon-grade-gray.png"></image>
    <image class="icon-star" src="../icons/icon-grade-gray.png"></image>
    <image class="icon-star" src="../icons/icon-grade-gray.png"></image>
  </view>
  <view class="star-gold" style='width:{{rate}}%'>
    <image class="icon-star" src="../icons/icon-grade.png"></image>
    <image class="icon-star" src="../icons/icon-grade.png"></image>
    <image class="icon-star" src="../icons/icon-grade.png"></image>
    <image class="icon-star" src="../icons/icon-grade.png"></image>
    <image class="icon-star" src="../icons/icon-grade.png"></image>
  </view>
</view>

样式:

css 复制代码
.star-wrap{display: inline-block;position: relative;}
.star-wrap .icon-star{width:15px;height:15px;}
.star-wrap .star-gold{overflow: hidden;white-space: nowrap;position: absolute;top: 0;left: 0;}

动态js:

javascript 复制代码
Component({
  properties:{
    grade:Number
  },
  data :{
    rate : 0
  },
  ready() {
      this.setData({
        rate : this.data.grade/5.0 * 100
      })
  },
  methods : {
    onload() {
      
    }
  }
})

以上部分是做好了五星好评的组件样式,现在需要在页面上展示:

引入组件json:

javascript 复制代码
{
  "usingComponents": {
    "fivestar-rater" : "../../components/fivestarrater"
  }
}

页面使用:

html 复制代码
       <view class="fivestar-wrap">
          <fivestar-rater grade="4.5"></fivestar-rater>
       </view>
       <view class="fivestar-wrap">
          <fivestar-rater grade="3.5"></fivestar-rater>
       </view>
       <view class="fivestar-wrap">
          <fivestar-rater grade="2.5"></fivestar-rater>
       </view>
       <view class="fivestar-wrap">
          <fivestar-rater grade="1.5"></fivestar-rater>
       </view>
       <view class="fivestar-wrap">
          <fivestar-rater grade="1"></fivestar-rater>
       </view>

最终效果:

在覆盖层设置宽度的时候,根据父页面传入的grade值,做了一个简单的计算。这里需要传入宽度百分比,但是样式在wxss文件中又不能写死,只能在wxml页面上通过style="width:xx%"的方式传入,这里有点不太优雅,本来css有个函数attr()可以获取元素属性值作为变量,并设置width属性值的。可是微信小程序这里并不支持这么做。可以使用attr()函数,但是不生效。但是在一般的web页面上是没问题的。

相关推荐
科研邪修法14 小时前
PDF新增页面文字与文本批注怎么区分?以双版本培训讲义为例
前端·css·pdf
Lanwarf-前端开发15 小时前
Vue3 + Canvas/WebGL 雷达扫描可视化实战:PPI、RHI、VOL、SVOL 四种模式原理与实现
前端·javascript·vue.js·webgl
FRing0316 小时前
vue3干货总结2(vue3生命周期、父子通信、模版引用、provide和inject)
开发语言·前端·vue.js·vue3
锋行天下17 小时前
langgraph 全栈项目(三)
前端·人工智能·后端
锋行天下18 小时前
langgraph 全栈项目(二)
前端·人工智能·后端
锋行天下19 小时前
langgraph全栈项目(一)
前端·人工智能·后端
叼烟扛炮20 小时前
[LangChain] 学习笔记(15):为什么你的重试没用——429、抖动、fallback 与熔断
java·服务器·前端
小码哥06820 小时前
智慧物业系统源码定制:公告发布范围与住户阅读记录设计
前端·javascript·vue.js·物业管理·物业系统·物业软件
泯泷1 天前
Cloudflare 出手抢 Astro:前端框架之战,底层逻辑变了
前端·javascript·前端框架