浅谈小程序怎么实现“五星评价”功能(支持点击+滑动)
本篇文章给大家介绍一下小程序实现“五星评价”功能的方法,支持实现点击评分、滑动评分。
小程序— 五星评价功能
1、已完成需求:
- 支持半星评价
- 点击评分
- 滑动评分
【相关学习推荐:小程序开发教程】
2、原理
/*wxss 一行内展示五颗星并设置其间距为30rpx*/.scoreContent {display: inline-block;}.starLen {margin-right: 30rpx;display: inline-block;}.scoreContent .starLen:last-child {margin-right: 0;}.star {width: 80rpx;height: 80rpx;vertical-align: text-bottom;display: inline-block;}
/*wxml 每个starLen元素上绑定 touchMove touchEnd tap事件*/<view> <block> <!-- 遍历评分列表 --> <view> <!-- 使用三目运算符来动态变化显示的是哪张图片,score是js中的分数,index是scoreArray的下标 --> <image>index?(score>index+0.5?fullStarUrl:halfStarUrl):nullStarUrl}}" /> </image></view> </block></view>
以上渲染中重要的是,三目运算所要展示的应该是哪种图标,index为scoreArray的元素下标,每一个item的下标index都要与score进行比较,规则如下:
//取 score与index下标做比较,默认score为0score<index score>index+0.5 展示fullStar.pngindex<score><ul><li><strong>data预设值</strong></li></ul><pre class="brush:js;toolbar:false;"> /** * 组件的初始数据 */ data: { fullStarUrl: '/images/full.png', //满星图片 halfStarUrl: '/images/half.png', //半星图片 nullStarUrl: '/images/null.png', //空星图片 score: 0, //评价分数 rate: 2, //设计稿宽度÷屏幕实际宽度 startX: 0, //第一颗星screenX的距离 },
//设定比率rate与第一颗星screenX 组件初始化attached 或者 页面初始化onShowattached: function () { // 在组件实例进入页面节点树时执行 let { screenWidth } = wx.getSystemInfoSync(); let rate = screenWidth / 750; this.setData({ rate: rate }) const query = this.createSelectorQuery(); query.select('#scoreContent').boundingClientRect((res)=> { this.setData({ startX: res.left }) }).exec()},
更多编程相关知识,请访问:编程视频!!