index.wxml
<view class="container"> <text>成绩: {{score}}</text> <view class="stars"> <block wx:for="{{stars}}" wx:key="index"> <image src="/images/stars_{{item}}.png" class="star-image"></image> </block> </view> </view>
index.wxss
.container { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; } .stars { display: flex; } .star-image { width: 30px; height: 30px; margin-right: 5px; }
index.js
Page({ data: { score: 0, // 初始成绩 stars: [] // 初始星级数组 }, onLoad: function() { // 假设我们从服务器获取到的成绩是85分 const scoreFromServer = 85; this.updateStars(scoreFromServer); }, updateStars: function(score) { const maxStars = 5; // 最大星级数 let stars = []; for (let i = 0; i < maxStars; i++) { if (score >= (i + 1) * 20) { stars.push('select'); // 假设'full'代表满星图片 } else if (score > i * 20) { stars.push('half'); // 假设'half'代表半星图片 } else { stars.push('unselect'); // 假设'empty'代表空星图片 } } this.setData({ score: score, stars: stars }); } });
WXML 文件:定义了一个展示成绩的文本和用于显示星级好评的视图。使用 wx:for
循环来动态生成星星图片。
WXSS 文件:定义了容器和星星图片的样式。
JS 文件:在 onLoad
方法中模拟从服务器获取成绩,并调用 updateStars
方法来更新星级数组。updateStars
方法根据成绩计算每个星星的显示状态(满星、半星或空星),并更新页面数据。
你可以根据需要调整成绩和星级之间的对应关系。在这个示例中,每20分代表一颗星星,80-89分显示4颗半星,以此类推。
示例中的图片文件名和路径需要根据实际项目进行调整。
微信小程序的图片路径相对于项目根目录,确保图片资源放置在正确的位置。
通过这种方式,你可以根据返回的数字成绩动态显示星级好评。