任務(wù)描述:想做一個(gè)遍歷所有元素然后點(diǎn)擊其中某個(gè)元素動(dòng)態(tài)的改變?cè)撛貥邮?,再次點(diǎn)擊會(huì)切換回原來(lái)的樣式,在整個(gè)過(guò)程中,只會(huì)改變點(diǎn)擊元素的樣式,并不會(huì)影響其余元素的樣式。網(wǎng)上也找過(guò)不少實(shí)現(xiàn),發(fā)現(xiàn)講述的都不是很清楚,尤其是代碼常常有bug,故整理這篇文章,代碼寫(xiě)的不怎么樣,關(guān)鍵是實(shí)現(xiàn)。
話不多說(shuō)上代碼:
WXML
<canvas canvas-id="myCanvas" style="border: 1px solid; width: 375px;height: 375px;margin-top: 15px;"
bindtouchstart="start"
bindtouchmove="move"
bindtouchend="end">
<movable-area style="height: 375px;width: 375px;">
<view wx:for="{{checkbox}}" data-key='{{index}}'>
<movable-view class="{{status[index]==0?'ttt1':'ttt2'}}" data-key='{{index}}' catchtap="change" direction="all" style=" background:pink ;">
{{index}}
</movable-view>
</view>
</movable-area>
</canvas>
<view hidden="{{hidden}}">
Coordinates: ({{x}}, {{y}})
</view>
<button style="width: 100px" bindtap="insert">增加按鈕</button>

這部分代碼和我的業(yè)務(wù)需求有關(guān),就是在一個(gè)區(qū)域內(nèi),通過(guò)點(diǎn)擊增加按鈕動(dòng)態(tài)添加元素,邏輯寫(xiě)在了js文件里,該元素我用的是可拖動(dòng)組件,換成普通的view也是一個(gè)道理。遍歷checkbox,也就是將所有的元素都輸出在界面上,通過(guò)status[index]來(lái)判斷以及改變每個(gè)元素的狀態(tài),因?yàn)槲疫@里一共就只有兩種樣式,所以我的狀態(tài)status也就只是0和1。這個(gè)status是一個(gè)狀態(tài)數(shù)組,可以理解為每個(gè)元素的狀態(tài)的一個(gè)集合,詳見(jiàn)js代碼部分。
通過(guò)點(diǎn)擊,只改變點(diǎn)擊的元素的樣式

JS
Page({
data: {
x: 0,
y: 0,
checkbox: [],
status: [],
current_id: 0,
hidden: true
},
start: function(e) {
this.setData({
hidden: false,
x: e.touches[0].x,
y: e.touches[0].y
})
},
move: function(e) {
this.setData({
x: e.touches[0].x,
y: e.touches[0].y
})
},
end: function(e) {
this.setData({
hidden: true,
})
},
change: function(e){
console.log("test");
let index = e.currentTarget.dataset.key;
console.log(index);
if(this.data.status[index] == 1){
this.data.status[index] = 0;
}else{
this.data.status[index] = 1;
}
this.setData({
status: this.data.status
});
console.log(this.data.checkbox)
},
insert: function() {
var cb = this.data.checkbox;
var sta = this.data.status;
cb.push(this.data.checkbox.length);
sta.push(0);
console.log(sta);
this.setData({
checkbox: cb,
status: sta
});
}
})
這部分的代碼就講兩個(gè)點(diǎn),insert函數(shù)中,每增加一個(gè)元素,同時(shí)在status數(shù)組重生成該元素的status,默認(rèn)為0,其實(shí)在這里我們化繁為簡(jiǎn)了,我一開(kāi)始想實(shí)現(xiàn)直接在元素的數(shù)組checkbox中直接添加status信息,但是因?yàn)檫@個(gè)數(shù)組是動(dòng)態(tài)添加的,沒(méi)有辦法去動(dòng)態(tài)添加這樣一個(gè)狀態(tài)信息。于是我們想到通過(guò)索引對(duì)應(yīng),新開(kāi)一個(gè)數(shù)組,一個(gè)索引的status就對(duì)應(yīng)到該索引下的checkbox元素;然后change事件中,每點(diǎn)擊一次待改變樣式的元素,都會(huì)進(jìn)行一次判斷,判斷該元素的status是0還是1,改變自身狀態(tài),原來(lái)是0就變成1,原來(lái)是1就變成0。
WXSS
/* pages/display/display.wxss */
.ttt1{
width: 100px;
height: 50px;
}
.ttt2{
width: 50px;
height: 100px;
}