小程序input的一些坑点
发布于 4 年前 作者 jiangtao 4867 次浏览 来自 分享

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

  1. 表单组件(input)如何阻止冒泡
  2. 在容器(fixed)中的input如何弹出键盘

阻止input冒泡

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

上例中input操作会冒泡到container,导致onTap响应执行

修正

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

冒泡的问题是由input的tap事件导致,因此定义一个empty的空方法,使它响应input的catch:tap,来达到阻止input的冒泡的作用

在容器(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;`
            })
        }
    }
})

GITHUB

demo

回到顶部