小程序实现点击星评 | 熊阿哥博客

小程序实现点击星评

微信   2025-02-08 15:58   91   0  

28793_livv_3900.png

index.wxml

<view class="star-rating" bind:tap="clickstar">
  <block wx:for="{{stars}}" wx:key="index">
    <image src="{{item.type === 'filled' ? '/images/stars_select.png' : '/images/stars_unselect.png'}}" mode="aspectFit" class="star"></image>
  </block>
</view>


index.wxss

.star-rating {
  display: flex;
  justify-content: space-between;
  width: 200px; /* 根据需要调整宽度 */
}

.star {
  width: 30px;  /* 星星宽度 */
  height: 30px; /* 星星高度 */
}


index.js

Page({
  data: {
    totalStars: 6,        // 总星星数
    score: 20,             // 当前成绩(0-6)
    stars: []            // 星星数组
  },

  onLoad: function(options) {
    // 初始化星星状态,默认全为灰色
    const initialStars = Array.from({ length: this.data.totalStars }, () => ({
      type: 'gray'
    }));
    this.setData({ stars: initialStars });
  },

  //点击设置显示高亮的星星
  clickstar(e){
    this.updateStars(3);
  },

  /**
   * 更新星星状态根据成绩
   * @param {Number} newScore - 新的成绩(0-6)
   */
  updateStars: function(newScore) {
    if (newScore < 0 || newScore > this.data.totalStars) {
      console.error('成绩超出范围');
      return;
    }

    const updatedStars = this.data.stars.map((star, index) => {
      return {
        type: index < newScore ? 'filled' : 'gray'
      };
    });

    this.setData({ 
      score: newScore,
      stars: updatedStars
    });
  }
});



博客评论
还没有人评论,赶紧抢个沙发~
发表评论
说明:请文明发言,共建和谐网络,您的个人信息不会被公开显示。