原創聲明:本文為作者原創,未經允許不得轉載,經授權轉載需注明作者和出處
在很多場景中我們會評價某些商品,從而讓其他后來者對某個商品有一定的參考意義,那么我們在小程序中應該如何實現呢?
評價效果
:效果圖
:<!--pages/main/main.wxml-->
<navigator url="../index/index">
<button class="mybtn" type="primary">打分</button>
</navigator>
<navigator url="../show/show">
<button class="mybtn" type="primary">顯示評分</button>
</navigator>
<!--index.wxml-->
<view >
<block wx:for="{{stars}}">
<image class="star-image" style="left: {{item*100}}rpx" src="{{key > item ?(key-item == 0.5?halfSrc:selectedSrc) : normalSrc}}">
<view class="item" style="left:0rpx" data-key="{{item+0.5}}" bindtap="selectLeft"></view>
<view class="item" style="left:50rpx" data-key="{{item+1}}" bindtap="selectRight"></view>
</image>
</block>
<view style="margin-top:450rpx">
<button bindtap="startRating">確認</button>
</view>
</view>
//index.js
var app = getApp()
var count = 0;
Page({
data: {
stars: [0, 1, 2, 3, 4],
normalSrc: '../../images/no-star.png',
selectedSrc: '../../images/full-star.png',
halfSrc:'../../images/half-star.png',
key: 0,//評分
},
onLoad: function () {
},
//點擊左邊,半顆星
selectLeft: function (e) {
var key = e.currentTarget.dataset.key
if (this.data.key == 0.5 && e.currentTarget.dataset.key == 0.5) {
//只有一顆星的時候,再次點擊,變為0顆
key = 0;
}
count = key
this.setData({
key: key
})
},
//點擊右邊,整顆星
selectRight: function (e) {
var key = e.currentTarget.dataset.key
count = key
this.setData({
key: key
})
},
startRating:function(e){
wx.showModal({
title: '分數',
content: ""+count,
success: function(res) {
if (res.confirm) {
console.log('用戶點擊確定')
}
}
})
}
})
<!--pages/show/show.wxml-->
<view class="stars">
<block wx:for="{{stars}}" wx:for-item="item">
<image src="../../images/{{item}}-star.png" class="star"></image>
</block>
<form bindsubmit="formSubmit" bindreset="formReset">
<input name="input" style="margin-bottom:20rpx" class="c_Input" placeholder="請輸入評分"/>
<button style="background-color:#0066FF;color:white" formType="submit">確定</button>
</form>
</view>
// pages/show/show.js
Page({
data:{
"stars":''
},
onLoad:function(options){
// 頁面初始化 options為頁面跳轉所帶來的參數
},
onReady:function(){
// 頁面渲染完成
},
onShow:function(){
// 頁面顯示
var that = this;
var renderData = {
"stars":that.starCount(0)
};
that.setData(renderData)
},
onHide:function(){
// 頁面隱藏
},
onUnload:function(){
// 頁面關閉
},
//計算行星顯示規則
starCount:function(originStars){
//計算星星顯示需要的數據,用數組stars存儲五個值,分別對應每個位置的星星是全星、半星還是空星
var starNum = originStars*10/10,stars = [],i = 0;
do{
if(starNum>=1){
stars[i] = 'full';
}else if(starNum>=0.5){
stars[i] = 'half';
}else{
stars[i] = 'no';
}
starNum--;
i++;
}while(i<5)
return stars;
},
formSubmit: function(event) {
var that = this;
var renderData = {
"stars":that.starCount(event.detail.value.input)
};
that.setData(renderData);
}
})