微信小程序:选择题目应用(选错提示正确答案),其实这个还是不错的,有时候我们需要这种功能,提示给小白用户。一起来看下如何实现呢。先看下效果图:
WXML代码:
<view class='selection'> <view class='{{view1}}' bindtap='view1Click' id='1'>a</view> <view class='{{view2}}' bindtap='view2Click' id='2'>b</view> <view class='{{view3}}' bindtap='view3Click' id='3'>c</view> <view class='{{view4}}' bindtap='view4Click' id='4'>d</view> </view>
JS代码:
Page({ /** * 页面的初始数据 */ data: { view1: 'selection1', view2: 'selection1', view3: 'selection1', view4: 'selection1', // 默认答案为2,后台会给的 key: 2, // 选项是否被点击 isSelect: false }, view1Click: function(e) { var select = e.target.id // 选项没被选择时将执行 if (!this.data.isSelect) { // 将选项设置为“已被选择” this.setData({ isSelect: true }) // 注意!此处必须是'=='而不是'=' if (select == this.data.key) { this.setData({ view1: 'selection2' }) } else { this.setData({ view1: 'selection3' }) // 将正确选项显示出来 this.showAnswer(this.data.key) } } }, view2Click: function(e) { var select = e.target.id // 选项没被选择时将执行 if (!this.data.isSelect) { this.setData({ isSelect: true }) // 注意!此处必须是'=='而不是'=' if (select == this.data.key) { this.setData({ view2: 'selection2' }) } else { this.setData({ view2: 'selection3' }) // 将正确选项显示出来 this.showAnswer(this.data.key) } } }, view3Click: function(e) { var select = e.target.id // 选项没被选择时将执行 if (!this.data.isSelect) { this.setData({ isSelect: true }) // 注意!此处必须是'=='而不是'=' if (select == this.data.key) { this.setData({ view3: 'selection2' }) } else { this.setData({ view3: 'selection3' }) // 将正确选项显示出来 this.showAnswer(this.data.key) } } }, view4Click: function(e) { var select = e.target.id // 选项没被选择时将执行 if (!this.data.isSelect) { this.setData({ isSelect: true }) // 注意!此处必须是'=='而不是'=' if (select == this.data.key) { this.setData({ view4: 'selection2' }) } else { this.setData({ view4: 'selection3' }) // 将正确选项显示出来 this.showAnswer(this.data.key) } } }, showAnswer: function(key) { // 通过swith语句判断正确答案,从而显示正确选项 switch (key) { case 1: this.setData({ view1: 'selection2' }) break; case 2: this.setData({ view2: 'selection2' }) break; case 3: this.setData({ view3: 'selection2' }) break; default: this.setData({ view4: 'selection2' }) } } })
WXSS代码:
.selection1{ width: 400rpx; height: 150rpx; background-color: grey; display: flex; flex-direction: column; justify-content: space-around; align-items: center; } .selection2{ width: 400rpx; height: 150rpx; background-color: blue; display: flex; flex-direction: column; justify-content: space-around; align-items: center; } .selection3{ width: 400rpx; height: 150rpx; background-color: red; display: flex; flex-direction: column; justify-content: space-around; align-items: center; } .selection{ width: 750rpx; height: 800rpx; display: flex; flex-direction: column; justify-content: space-around; align-items: center; }
大家可以把代码放到开发软件里去测试下,看下效果,希望能帮助到大家。
网友评论文明上网理性发言 已有0人参与
发表评论: