微信小程序笔记--显示五星好评(注意是显示不是点击评价!)

网上看了好多都是点击事件实现五星评价,想做一个只显示五星的微信小程序模板,结果网上都不全,所以还是自己写一个免得忘记,学艺不精,如果你有更好的方法请一定要留下评论或者私信给我,十分感谢!

1、先上一个效果图,就是出镜率超高的豆瓣电影小程序(微信上面叫 “豆瓣评分”)。


2、因为是五星显示,所以第一步要先除以2,如果你想显示十星的话就不用除以2了,在设置空星的时候把length改为10就行。以下是js源码:

onLoad: function(options) {
    var that = this;
    wx.showLoading({
      title: '拼命加载中....'
    })
    wx.request({
      url: API_URL,
      data: {},
      success: function(res) {
        wx.hideLoading()
        var dataList = res.data.data;
        for (var i=0; i<dataList.length;i++) {
          dataList[i].stars = []  //添加需要的star数组
          var data = dataList[i].score / 2  //除以2,以便换5星
          var score = Math.floor(data * 2) / 2;  //四舍五入
          var hasDEcimal = score % 2 !== 0; //判断奇偶
          var integer = Math.floor(score);  //取整
          for (var n=0; n<integer; n++) { //整数添加满星
            dataList[i].stars.push(1);
          }
          if (hasDEcimal) {   //奇数添加半星
            dataList[i].stars.push(2)
          }
          while (dataList[i].stars.length < 5) {  //其余为空星
            dataList[i].stars.push(0)
          }
        }
        that.setData({
          movieList: dataList
        })
      }
    })
  }

我是直接写在onload方法里面的,如果有更好的方法请一定要告知,谢谢!

ps : Math.floor(x)返回小于或等于数字的最大整数x

3、因为用到的地方比较多,所以我直接写成一个star模板,以下是模板的wxml,wxss代码。

<template name="starsTemplate">
  <view class='stars-container'>
    <view class='stars'>
      <block wx:for="{{stars}}" wx:key='position'>
        <image wx:if='{{item == 1}}' src='../../images/on.png' class='star-img'></image>
        <image wx:elif='{{item == 2}}' src='../../images/half.png' class='star-img'></image>
        <image wx:else src='../../images/off.png' class='star-img'></image>
      </block>
    </view>
    <text class='star-text'>{{score}}</text>
  </view>
</template>
.stars-container {
  display: flex;
  flex-direction: row;
  margin-top: 5px;
  position: relative;
}

.stars {
  display: flex;
  flex-direction: row;
    margin-top: 3px;
    margin-right: 15px;
}

.star-img {
  height: 10px;
  width: 10px;
  margin-right: 3px;
}

.star-text {
  color: #4a6164;
  font-size: 12px;
}

4、最后直接在需要用到的页面引用即可,如下

  <import src="../../public/star.wxml"/>
  <view>
     <template is="starsTemplate" data="{{stars: item.stars, score: item.score}}"/>
  </view>

5、最重要的是不要忘记在同一wxss文件中引入css样式!!!

@import "../../public/star.wxss";

搞定! 如果有需要全部源码(全部 = 这个页面,因为其他还没做完。。)可以私信我


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值