htmlCopy Code
<view class="star-rating">
<movable-area class="movable-area">
<movable-view class="movable-view" direction="horizontal" x="{{positionX}}" bindtouchmove="handleTouchMove"></movable-view>
</movable-area>
<view class="stars">
<view class="star" wx:for="{{stars}}" wx:key="index" bindtap="handleTapStar" data-index="{{index}}">
<image class="star-img" src="{{starUrl}}"></image>
</view>
</view>
<view class="rating-value">当前评分:{{rating}}</view>
</view>
cssCopy Code/* CSS 样式 */
.
star-rating {
display: flex;
flex-direction: column;
align-items: center;
padding-top: 20px;
}
.stars {
display: flex;
justify-content: space-between;
width: 200px;
}
.star {
position: relative;
width: 30px;
height: 30px;
}
.star-img {
width: 100%;
height: 100%;
}
.movable-area {
width: 200px;
height: 30px;
background-color: #eee;
}
.movable-view {
width: 30px;
height: 30px;
background-color: transparent;
}
.rating-value {
margin-top: 20px;
}
javascriptCopy Code// JS 代码
Page({
data: {
stars: [1, 2, 3, 4, 5], // 星星数量
starUrl: "/images/star.png", // 星星图片路径
positionX: 0, // movable-view 的 x 偏移量
rating: 0 // 当前评分
},
handleTouchMove: function (e) {
const touch = e.touches[0];
// 获取手指在 movable-view 内的横向偏移量
const offsetX = touch.clientX - 100;
// 将偏移量转换为合法范围内的值(0 ~ 4)
let positionX = Math.max(0, Math.min(offsetX, 120));
// 根据偏移量计算评分值(0 ~ 5)
const rating = Math.ceil(positionX / 24) + 1;
this.setData({
positionX: positionX,
rating: rating
});
},
handleTapStar: function (e) {
const index = e.currentTarget.dataset.index;
// 设置 movable-view 的位置和评分值
this.setData({
positionX: index * 24,
rating: index + 1
});
}
});