小程序input的一些坑点

4,182 阅读2分钟

最近在开发中遇到的一些坑点

  • 表单组件的层级
  • 表单组件(input)如何阻止冒泡
  • 在容器(fixed)中的input如何弹出键盘

表单组件的层级

小程序的表单组件层级非常高,我们需要为表单添加一个ICON,却不能使其触发响应的事件

如上图1,下拉菜单的icon,我们的解决方案是绑定focus事件在input上,icon作为浮层只是展示作用

如上图2,密码表单,icon必须能够点击,这里的解决方案是将两个结构并排排列

阻止input冒泡

<view bind:tap="onTap" class="container">
    <input bindinput="onBindInput" type="text"/>
</view>

解决方法

<view bind:tap="onTap" class="container">
    <input bindinput="onBindInput" type="text" catch:tap="empty"/>
</view>

input有tap操作,改操作会冒泡到下层的container结构上,导致container的onTap响应执行,既然如此,我们只需要解决input的tap冒泡的问题,解决方案中,构建一个空方法,使其响应input的catch:tap事件,则解决了冒泡问题

在容器(fixed)中的input如何弹出键盘

<view class="container" style="position: fixed; bottom: 0">
    <input bindinput="onBindInput" type="text"/>
</view>

container组件在屏幕底部出现,点击Input组件时,弹出的键盘会遮盖input输入框

修正

<view class="container" style="position: fixed; bottom: 0; {{mystyle}}">
    <input bindinput="onBindInput" bindkeyboardheightchange="onkeybord" type="text"/>
</view>
Page({
    data: {
        mystyle: '',
    },
    
    onkeybord(e){
        let detail = e.detail
        let kbHeight = detail.height
        if (kbHeight === 0) {
          this.setData({
              mystyle: ' '
          })
        }

        if (kbHeight && kbHeight > 0) {
            this.setData({
                mystyle: `bottom: ${kbHeight-40}px;`
            })
        }
    }
})

下列小程序DEMO包含下拉菜单、通用型筛选列表、索引列表、markdown(包含表格)、评分组件、水果老虎机、折叠面板、双栏分类导航(左右)、刮刮卡、日历等组件