uniapp实现滑动点击评分效果,支持满星 半星 不亮效果
代码如下
<template>
<view class="star-container" @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd"
@click="handleStarClick">
<view v-for="(star, index) in totalStars" :key="index" class="star-wrapper">
<view class="star" :data-index="index"
:class="{ 'full': index + 1 <= rating, 'half': index + 0.5 <= rating && rating < index + 1, 'empty': index + 1 > rating && index + 0.5 > rating }">
</view>
</view>
<view>{{rating}}</view>
</view>
</template>
<script>
export default {
data() {
return {
rating: 0,
startX: 0,
lastRating: 0 // 用于存储滑动前的评分
};
},
props: {
totalStars: {
type: Number,
default: 5
}
},
methods: {
handleTouchStart(event) {
this.startX = event.touches[0].clientX;
this.lastRating = this.rating; // 存储滑动前的评分
},
handleTouchMove(event) {
let offset = event.touches[0].clientX - this.startX;
let rating = this.lastRating + offset / 30; // 30为每颗星的宽度
if (rating < 0) rating = 0;
if (rating > this.totalStars) rating = this.totalStars;
this.rating = Math.ceil(rating * 2) / 2; // 四舍五入到最近的半星
},
handleTouchEnd(event) {
},
handleStarClick(event) {
const starIndex = event.target.dataset.index;
if (starIndex !== undefined) {
const index = parseInt(starIndex);
if (index + 1 === this.rating) {
this.rating = index; // 如果点击的是已经点亮的星星,则取消点亮
} else {
this.rating = index + 1; // 点击的是未点亮的星星,则点亮
}
}
}
}
};
</script>
<style scoped>
.star-container {
display: flex;
margin-top: 60px;
}
.star-wrapper {
/* 调整星星之间的边距 */
margin-right: 5px;
}
.star {
/* 定义星星的大小 */
width: 30px;
height: 30px;
background-image: url('未点亮的图片');
background-size: cover;
}
.full {
background-image: url('点亮的图片');
}
.half {
background-image: url('半点亮的图片');
}
.empty {
background-image: url('未点亮的图片');
}
</style>