前言
現(xiàn)在是2019年1月初伺绽,小程序官方還沒有發(fā)布cover-input
等組件嗜湃,在map層級之上可操作的組件只有cover-view
澜掩、cover-image
正文
map組件屬于原生組件,層級最高肩榕,能在map層級之上可操作的組件只有cover-view
株汉、cover-image
,現(xiàn)有需求在map組件上層浮現(xiàn)彈框乔妈,可選擇(select)
小程序提供picker選擇,但是在彈框modal上顯然不符合需求勃刨,需要自己重新實現(xiàn)。
在cover-view標(biāo)簽里實現(xiàn)cover-select是根據(jù)點擊事件控制select-list的顯示和隱藏身隐,在list中選中的item放到顯示區(qū)
實現(xiàn)思路:
- 用一個cover-view顯示選擇的內(nèi)容唯灵,沒有選擇時顯示初始化內(nèi)容;
- 給顯示內(nèi)容的cover-view綁定點擊事件早敬,控制選擇list的顯示和隱藏;
- 選擇的內(nèi)容最后放在顯示內(nèi)容的cover-view中水孩;
使用data-*
共同屬性將選中的item傳出
重點知識:
關(guān)于e.target和e.currentTarget的區(qū)別:
- e.target是返回觸發(fā)事件的對象
- e.currentTarget返回的是綁定事件的對象
通常情況下target和currentTarget是一致的琐驴,我們只要使用target即可,但有一種情況必須區(qū)分這兩者的關(guān)系绝淡,那就是在父子嵌套的關(guān)系中,父元素綁定了事件悬包,單擊了子元素(根據(jù)事件流馍乙,在不阻止事件流的前提下他會傳遞至父元素垫释,導(dǎo)致父元素的事件處理函數(shù)執(zhí)行)撑瞧,這時候currentTarget指向的是父元素,因為他是綁定事件的對象预伺,而target指向了子元素,因為他是觸發(fā)事件的那個具體對象
核心代碼:
<!-- cover-select實現(xiàn)偽代碼 -->
<cover-view class="cover-select" style="{{selectHeight}}">
<cover-view class='selected' bindtap='tapSelect'>{{selectModel}}</cover-view>
<cover-view class='select-list'>
<cover-view class='select-item' style="{{ item.value === selectValue ? 'color:green' : ''}}" wx:for='{{selectList}}' wx:key='{{item.value}}' data-value='{{item.value}}' bindtap='chooseItem'>{{item.label}}</cover-view>
</cover-view>
</cover-view>
<!-- cover-select實現(xiàn)偽代碼 -->
.cover-select{
background-color: #ffffff;
width: 80%;
position: relative;
left: 50%;
transform: translateX(-50%);
border-radius: 5rpx;
padding: 0 15rpx;
}
.selected{
line-height: 40px;
}
.select-list {
overflow-y: scroll;
max-height: 120px;
}
.select-item{
line-height: 30px;
}
.select-item:hover{
background-color: #f2f2f2;
}
Page({
data: {
latitude: 23.099994,
longitude: 113.324520,
selectHeight: 'height: 40px', // select 組件的高度
selectList: [{
label: 'name',
value: '1'
}, {
label: 'age',
value: '2'
}, {
label: 'sex',
value: '3'
}, {
label: 'label',
value: '4'
}, {
label: 'value',
value: '5'
}], // select 組件的可選項
selectModel: '選擇', // cover-view 顯示的選中的內(nèi)容
selectValue:''
},
onReady: function(e) {
this.mapCtx = wx.createMapContext('myMap')
},
/**
* 顯示 Select
*/
tapSelect() {
this.setData({
selectHeight: 'max-height:200px;'
})
},
/**
* 初始化選中item
*/
itemChosen() {
},
/**
* 選擇 item
*/
chooseItem(e) {
console.log(e.target.dataset.value);
let value = e.target.dataset.value;
let item = this.data.selectList.find((item) => item.value === value);
this.setData({
selectValue:item.value,
selectModel: item.label,
selectHeight: 'height:40px;'
})
}
})
效果圖:
初始化狀態(tài):
選擇時:
選擇后:
備注
源碼請點:
cover-select源碼
系列文章:
「小程序」map組件層級之上實現(xiàn)cover-input
「小程序」map組件層級之上實現(xiàn)cover-process-control
【敬請期待】