一个简单的小程序的评分组件,
在父组件传入key值:
- key的值为0时,用户可以点击星星进行评分操作,
- key的值不为0时,则只显示评分,用户没有点击操作
组件(star)目录和组件效果:
下面是具体代码:
//star.html
<view class='starbox'>
<text class='startext'>综合评分</text>
<view class='imgbox' wx:if="{{showTap}}" >
<block wx:for="{{stars}}" wx:key="{{item}}">
<image class="star-image" style="left: {{item*80}}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:35rpx" data-key="{{item+1}}" bindtap="selectRight"></view>
</image>
</block>
</view>
<view class='imgbox' wx:else>
<block wx:for="{{stars}}" wx:key="{{item}}">
<image class="star-image" style="left: {{item*80}}rpx" src="{{key > item ?(key-item == 0.5?halfSrc:selectedSrc) : normalSrc}}">
</image>
</block>
</view>
</view>
//star.css
.starbox{
display: flex;
}
.startext {
font-size: 14px;
height: 70rpx;
line-height: 70rpx;
color: #353535;
}
.imgbox {
flex: 1;
position: relative;
width: 550rpx;
}
.star-image {
position: absolute;
top: 0;
left: 0;
/* margin-left: 50rpx; */
width: 70rpx;
height: 70rpx;
src: "../images/no-star.png";
}
.item{
position: absolute;
top: 0rpx;
width: 35rpx;
height: 70rpx;
}
//star.js
Component({
properties:{
key:{
value: 0,//评分
type:Number
}
},
data: {
stars: [0, 1, 2, 3, 4],
normalSrc: '../images/no-star.png',
selectedSrc: '../images/full-star.png',
halfSrc: '../images/half-star.png',
showTap:true//是否可以点击
},
methods: {
//点击左边,半颗星
selectLeft: function (e) {
var key = e.currentTarget.dataset.key
if (this.data.key == 0.5 && e.currentTarget.dataset.key == 0.5) {
//只有一颗星的时候,再次点击,变为0颗
key = 0;
}
this.setData({
key: key
})
},
//点击右边,整颗星
selectRight: function (e) {
// count = key
this.setData({
key: key
})
},
},
attached: function () {
if (this.properties.key!=0){
this.setData({
showTap: false
})
}
}
})
在父组件(这里是index)使用:
//index.html
<view class="container">
<star key="{{key}}"></star>
</view>
//index.js
Page({
data:{
key: 0,//评分
}
})
//index.json
{
"usingComponents": {
"star": "../../star/star"
}
}
最后附上三张图片: