iOS微信小程序键盘弹出时输入框被挡住

1,204 阅读1分钟
1. 背景:

底部输入框采用fixed定位后,在iPhone13这种有底部安全区的手机上,键盘弹出时被遮挡,在安卓机上是正常的。

image.png

2. 查找问题:

看了网上的解决方案说设置“adjust-position”,试了一下没效果,本来现在这个属性也是默认为true的,看网上另一个解决方案就是判断键盘弹出时,手动改变bottom值,实测是可以的,注意需要为input添加adjust-position="false",不然在重复弹起时,有时候会生效,导致错乱。

3. 解决方案关键代码
<template>
    <view class="page">
        <view class="footer footer-space" :style="{bottom: `${keyboardHeight}px`}">
          <input 
            v-model="commentInput" 
            :adjust-position="false"
            placeholder="输入"
          ></input>
        </view>
    </view>
 </template>
 <script>
 export default {
    data() {
        return {
            keyboardHeight: 0, // 键盘高度
        }
    },
    onLoad() {

        let iphoneSafeHeight = 0 // ios安全区高度
        //获取屏幕信息
        uni.getSystemInfo({ 
            success(res) { 
                iphoneSafeHeight = res.screenHeight -  res.safeArea.bottom
            }
        })
        // 监听键盘变化
        uni.onKeyboardHeightChange(res => {
          this.keyboardHeight = res.height > 0 ? res.height - iphoneSafeHeight : res.height // 有安全区时需要减去该高度,不然还是会被挡住
        })
    }
 }
 </script>
 <style lang="scss" scoped>
 .footer {
    position: fixed;
    bottom: 0;
    left: 0;
    display: flex;
    align-items: center;
    border-top: 2rpx solid rgba(0,0,0,0.1);
    padding: 20rpx 28rpx;
    width: 100%;
    box-sizing: border-box;
    font-size: 28rpx;
    background: #fff;
}
.footer-space {
    padding-bottom: constant(safe-area-inset-bottom) !important; /* 兼容 iOS < 11.2 */
    padding-bottom: env(safe-area-inset-bottom) !important; /* 兼容 iOS >= 11.2 */
}
 </style>
4. 思考:

input的“adjust-position”属性没用的原因,应该是我包多了一层div,定位的实际是footer层了。