微信小程序map组件层级之上实现input
最近在开发一个租车小程序,着实被原生组件Map折磨的很惨。
今天说的是在地图上实现一个input输入框。
Map组件时微信的最高层级原生组件,具有最高优先级无视z-index,其他最高层级原生组件包括video、canvas、camera等。
Map组件上无法识别view、input,会被Map始终覆盖,只支持cover-view、cover-image。
在真机上原生input组件嵌在内会被忽略导致
实现思路:
- input用来输入内容,在真机上input组件嵌在内虽然会被忽略,但是点击依旧可以获取焦点;
- 用一个cover-view显示输入的内容,显示内容的cover-view覆盖在input标签上,使视觉上做到cover-input效果;
- 控制input的焦点可以在真机上做到cover-input效果,在input失去焦点后赋值给显示内容的cover-view;
下面展示一些 内联代码片
。
<view class="page-section">
<map id="myMap" style="width: 100%; height: 500px;" latitude="{{latitude}}" scale="18" longitude="{{longitude}}" show-location>
<cover-image class="center-point" src="/image/location-red.png"></cover-image>
<!-- 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伪代码实现 -->
</map>
</view>
data: {
latitude: 23.099994,
longitude: 113.324520,
inputFocus: false, // input 框的focus状态
inputModel: '', // input 框的输入内容
inputInfo: '输入', // cover-view 显示的 input 的输入内容,初始值充当placeholder作用
},
onReady: function(e) {
this.mapCtx = wx.createMapContext('myMap');
},
// 将焦点给到 input(在真机上不能获取input焦点)
tapInput() {
this.setData({
//在真机上将焦点给input
inputFocus: true,
//初始占位清空
inputInfo: ''
});
},
// input 失去焦点后将 input 的输入内容给到cover-view
blurInput(e) {
this.setData({
inputInfo: e.detail.value || '输入'
});
}
.page-section{
box-sizing: border-box;
padding: 0 30rpx;
}
.center-point {
height: 30px;
width: 30px;
position: relative;
top: calc(50% - 15px);
left: 50%;
transform: translate(-50%, -50%);
}
.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;
}
文章内容转载 夏知更