前言
現在是2019年1月初,小程序官方還沒有發布cover-input
等組件,在map層級之上可操作的組件只有cover-view
、cover-image
正文
map組件屬于原生組件,層級最高,能在map層級之上可操作的組件只有cover-view
、cover-image
,現有需求在map組件上層浮現彈框,可輸入(input)
在真機上原生input組件嵌在<cover-view />內會被忽略導致
實現思路:
- input用來輸入內容,在真機上input組件嵌在<cover-view />內雖然會被忽略,但是點擊依舊可以獲取焦點;
- 用一個cover-view顯示輸入的內容,顯示內容的cover-view覆蓋在input標簽上,使視覺上做到cover-input效果;
- 控制input的焦點可以在真機上做到cover-input效果,在input失去焦點后賦值給顯示內容的cover-view;
核心代碼:
<!-- cover-input偽代碼實現 -->
<cover-view class='cover-input' bindtap='tapInput'>
<cover-view class='text'>{{inputInfo}}</cover-view>
<input class='input' value='{{inputModel}}' focus='{{inputFocus}}' bindblur='blurInput'></input>
</cover-view>
<!-- cover-input偽代碼實現 -->
.cover-input{
width: 80%;
height: 32px;
line-height: 32px;
border-radius: 5px;
background-color: rgba(255, 255, 255, 0.9);
position: relative;
left: 50%;
transform: translateX(-50%);
padding-left: 15rpx;
padding-right: 15rpx;
}
.text{
height: 32px;
line-height: 32px;
}
.input{
height: 32px;
line-height: 32px;
/* margin-top為text的高度,保持視覺上一致 */
margin-top: -32px;
}
/**
* 將焦點給到 input(在真機上不能獲取input焦點)
*/
tapInput() {
this.setData({
//在真機上將焦點給input
inputFocus:true,
//初始占位清空
inputInfo: ''
});
},
/**
* input 失去焦點后將 input 的輸入內容給到cover-view
*/
blurInput(e) {
this.setData({
inputInfo: e.detail.value || '輸入'
});
}
效果圖:
初始化狀態:
真機初始化效果圖
輸入后:
真機輸入后效果圖
備注
源碼請點:
cover-input源碼
系列文章:
「小程序」map組件層級之上實現cover-select
「小程序」map組件層級之上實現cover-process-control
【敬請期待】