您的位置:首页 > 移动开发 > 微信开发

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

2018-07-10 18:09 489 查看

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

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";
搞定! 如果有需要全部源码(全部 = 这个页面,因为其他还没做完。。)可以私信我


阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: