這段時(shí)間做項(xiàng)目毫蚓,看到有需求不用字體圖標(biāo)的五角星占键,只能用圖片的,百度一下元潘,畔乙,感覺(jué)不錯(cuò)正好拿來(lái)收藏。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>星星打分</title>
</head>
<body>
<div id="app" class="row">
<div class="form-group clearfix">
<label class="control-label col-md-4">星星數(shù)量:{{starNum}}分</label>
<div class="col-md-8">
<div class="grade-box">
<img v-for="(star,index) in stars" v-bind:src="star.src" v-on:click="rating(index)" alt="星星圖片" />
</div>
</div>
</div>
</div>
<script src="vue.js"></script>
<script>
//星星的圖片路徑
var starOffImg = "img/starOff.png";
var starOnImg = "img/starOn.png";
var app = new Vue({
el: "#app",
data: {
stars: [{
src: starOffImg,
active: false
}, {
src: starOffImg,
active: false
}, {
src: starOffImg,
active: false
},
{
src: starOffImg,
active: false
}, {
src: starOffImg,
active: false
}
],
starNum: 0,
},
methods: {
//評(píng)分
rating: function(index) {
var total = this.stars.length; //星星總數(shù)
var idx = index + 1; //這代表選的第idx顆星-也代表應(yīng)該顯示的星星數(shù)量
//進(jìn)入if說(shuō)明頁(yè)面為初始狀態(tài)
if(this.starNum == 0) {
this.starNum = idx;
for(var i = 0; i < idx; i++) {
this.stars[i].src = starOnImg;
this.stars[i].active = true;
}
} else {
//如果再次點(diǎn)擊當(dāng)前選中的星級(jí)-僅取消掉當(dāng)前星級(jí)柬批,保留之前的啸澡。
if(idx == this.starNum) {
for(var i = index; i < total; i++) {
this.stars[i].src = starOffImg;
this.stars[i].active = false;
}
}
//如果小于當(dāng)前最高星級(jí),則直接保留當(dāng)前星級(jí)
if(idx < this.starNum) {
for(var i = idx; i < this.starNum; i++) {
this.stars[i].src = starOffImg;
this.stars[i].active = false;
}
}
//如果大于當(dāng)前星級(jí)氮帐,則直接選到該星級(jí)
if(idx > this.starNum) {
for(var i = 0; i < idx; i++) {
this.stars[i].src = starOnImg;
this.stars[i].active = true;
}
}
var count = 0; //計(jì)數(shù)器-統(tǒng)計(jì)當(dāng)前有幾顆星
for(var i = 0; i < total; i++) {
if(this.stars[i].active) {
count++;
}
}
this.starNum = count;
}
},
}
})
</script>
</body>
</html>
原文鏈接:https://blog.csdn.net/qq_16371909/article/details/79352348