uniapp实现滑动点击评分效果,支持满星 半星 不亮效果

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>
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值