一個簡單的小程序的評分組件,
在父組件傳入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"
}
}
最後附上三張圖片: