小程序输入需要高亮显示的星评(点击和自动显示) | 熊阿哥博客

小程序输入需要高亮显示的星评(点击和自动显示)

微信   2025-02-08 16:01   68   0  

29109_n6t4_4187.png

11058_owbo_2121.png

11059_fqdh_5653.png

index.wxml

<input type="number" bindinput="onScoreInput" placeholder="输入成绩(0-6)" />
<button bindtap="onSubmit">提交</button>

<!-- 第一种方法:输入0-6的数字,点击提交按钮来高亮展示星星 -->
<star-rating id="star-rating" current-score="{{currentScore}}"></star-rating>

<!-- 第二种方法:输入0-6的数字自动高亮展示星星 -->
<star-rating id="star-rating" score="{{currentScore}}"></star-rating>

<!-- 第三种方法 -->
<!--
  <input type="number" bindinput="onScoreChange" placeholder="输入成绩(0-6)" />
  <star-rating score="{{currentScore}}"></star-rating> 
  index.js设置:
  Page({
  data: {
    currentScore: 0
  },

  onScoreChange: function(newScore) {
    this.setData({ currentScore: newScore });
  }
});
-->


index.json

{
  "usingComponents": {
    "star-rating":"/components/star13/index"
  }
}


index.js

// const StarRating = require('../../../components/star13/index');
Page({
  data: {
    currentScore: 0
  },

  onScoreInput: function (e) {
    const score = parseInt(e.detail.value);
    this.setData({
      currentScore: score
    });
  },

  onSubmit: function () {
    this.selectComponent('#star-rating').updateStars(this.data.currentScore);
  }
});


新建组件文件:

/components/star13/index.wxml

<view class="star-rating">
  <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>


/components/star13/index.js

Component({
  properties: {
    score: {
      type: Number,
      value: 0,
      observer: function(newVal) {
        this.updateStars(newVal);
      }
    }
  },

  data: {
    totalStars: 6,
    stars: []
  },

  attached: function() {
    const initialStars = Array.from({ length: this.data.totalStars }, () => ({
      type: 'gray'
    }));
    this.setData({ stars: initialStars });
  },

  methods: {
    updateStars: function(newScore) {
      if (newScore < 0 || newScore > this.data.totalStars) {
        console.error('成绩超出范围');
        return;
      }

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

      this.setData({ stars: updatedStars });
    }
  }
});


/components/star13/index.wxss

.star-rating{
  display:inline;
}

.star-rating image{
  width:40px;
  height:40px;
  display:inline-block;
}







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