分享一下写的很多评价系统常用的打星评价的星星组件,单独提取出的组件可以直接使用。
发出来的目的是因为自己也写过一次,但是代码搞丢了,这次用到了又重新写了一个,干脆发到博客上,方便自己查看。
WXML文件:
<view class="starArea" >
<view class="starBox" data-id="{{index}}" wx:for="{{array}}" bindtouchstart="scoringStart" bindtouchmove="moveing" bindtouchend="scoringEnd">
<image class="star" src="{{item}}"></image>
</view>
</view>
WXSS文件:
.starArea{
height: 50rpx;
display: flex;
}
.starBox{
height: 50rpx;
width: 50rpx;
display: flex;
justify-content: center;
align-items: center;
}
.star{
width: 45rpx;
height: 45rpx;
}
JS文件:
Component({
/**
* 组件的属性列表
*/
properties: {
//分数 10分制
score: {
type: Number,
value: '',
observer: function (newVal, oldVal, changedPath) {
this.createStar(newVal)
}
},
//是否不可打分编辑 默认值不可打分
edit: {
type: Boolean,
value: true,
observer: function (newVal, oldVal, changedPath) {
this.setData({
noEdit: newVal
})
}
}
},
/**
* 组件的初始数据
*/
data: {
array:[],
starFull:'/images/xin2.png',
starHalf:'/images/banke.jpg',
starNull:'/images/xin1.png',
noEdit:false,
x:0
},
/**
* 组件的方法列表
*/
methods: {
createStar: function (newVal){
this.data.array = [];
this.data.score = newVal;
for (let i = 10; i > 0; i -= 2) {
newVal = newVal - 2;
if (newVal >= 0) {
this.data.array.push(this.data.starFull);
}
//半颗星
// else if (newVal==-1){
// this.data.array.push(this.data.starHalf);
// }
else {
this.data.array.push(this.data.starNull);
}
}
this.setData({
array: this.data.array
})
},
scoringStart:function(e){
if (this.data.noEdit)return;
let index = e.currentTarget.dataset.id
for(let i = index;i>=0;i--){
this.data.array[i] = this.data.starFull
}
for (let i = index+1; i <= 4; i++) {
this.data.array[i] = this.data.starNull
}
this.data.score = index*2;
this.setData({
array: this.data.array
})
this.data.x = e.changedTouches[0].pageX
},
scoringEnd:function (e) {
if (this.data.noEdit) return;
this.triggerEvent("score", { score: this.data.score})
},
moveing: function (e) {
// 移动触发频率过高,渲染页面不合适。
}
}
设计仅有五颗星,后来取消的半颗星,那段注释掉了。
有需要的朋友自取。
在下设计拙劣,有更好设计建议,欢迎大家指正。