小程序实现滑动和点击星星评分

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
    });
  }
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值