場(chǎng)景:畫圖應(yīng)用需選擇畫筆顏色,有4種顏色按鈕可供選擇,用戶點(diǎn)擊任意按鈕進(jìn)行顏色切換。 思路:通過curColorIndex變量保存當(dāng)前選中的顏色下標(biāo),選中后添加額外的選中樣式 ... ... ... ... ... ... ... ... ...

場(chǎng)景:畫圖應(yīng)用需選擇畫筆顏色,有4種顏色按鈕可供選擇,用戶點(diǎn)擊任意按鈕進(jìn)行顏色切換。
思路:通過curColorIndex變量保存當(dāng)前選中的顏色下標(biāo),選中后添加額外的選中樣式
一,canvas.wxss文件:這個(gè)文件用于定義按鈕正常態(tài)和選中態(tài)的樣式,以及Flex
布局的約束
/*容器布局*/.color_right_area {margin-top: 30rpx;display: flex;flex-direction: row;align-items: center;justify-content: space-around;}/*正常效果:圓形*/.box {width: 45rpx;height: 45rpx;border-radius: 50%;background-color: rebeccapurple;}/*選中效果:帶邊框*/.is_checked {width: 47rpx;height: 47rpx;border: 2px solid;}/*按鈕顏色樣式*/.color0 {background-color: #d5243e;}.color1 {background-color: #318ff4;}.color2 {background-color: #f9a23f;}.color3 {background-color: #000;}二,canvas.wxml文件:這個(gè)文件是Demo的布局界面,通過使用js的data數(shù)據(jù)和wxss的class樣式進(jìn)行頁面布局
class="color_right_area"> class='color_right_area' wx:for='{{data_color}}' wx:key='id'> class="box color{{index}} {{curColorIndex==index?'is_checked':'color{{index}}'}}" bindtap="colorSelect" data-param='{{index}}'> 這里通過wx:for實(shí)現(xiàn)循環(huán)打印顏色數(shù)組,通過curColorIndex值控制選中的樣式,index值進(jìn)行參數(shù)傳遞
三,canvas.js文件:提供數(shù)據(jù),以及處理xwml的控件響應(yīng),并通過設(shè)置this.setData的值來更新xwml的顯示
Page({data: {curColorIndex:0, data_color: [],},//更改畫筆顏色的方法colorSelect: function (e) {let curIndex = parseInt(e.currentTarget.dataset.param)this.setData({curColorIndex: curIndex});},onLoad: function () {let init_color = ['#d5243e','#318ff4','#f9a23f','#ffffff']this.setData({ data_color: init_color})}})onLoad:function這個(gè)函數(shù)在頁面加載時(shí)就會(huì)執(zhí)行一次,所以這里可以加載默認(rèn)顏色數(shù)據(jù),同時(shí)wxml用到了curColorIndex以及data_color,所以在data里定義。