uni-app 监听软键盘高度问题:使用HBuilderX运行时正常,打包为APP后失效

uni-app 监听软键盘高度问题:使用HBuilderX运行时正常,打包为APP后失效

开发环境 版本号 项目创建方式
Windows 10专业版 HBuilderX

示例代码:

<view class="noticeBottom" style="{'position': 'fixed','top': 'auto','left': 0,'right': 0,'bottom': commentFocus ? 0 : '-200rpx'}"> <view class="inputBox"> <input ref=“noticeInput” v-model=“commentVale” type=“text” :focus=“commentFocus”
placeholder=“commentFocus ? commentPla : ‘说点什么吧’” confirm-type=“send” cursor-spacing=“12” auto-blur=“true” :adjust-position=“false” @confirm="$u.throttle(dianpingClick, 500)" @blur=“dianpingBlur” /> <view class="bqImgBox"> <image src="/static/icon_anniu.png" mode="aspectFill"></image> </view> </view> <view class=“btnBox” @click.stop=“dianpingClick(123)”>发布</view> </view>



onShow() {
uni.onKeyboardHeightChange(res => {
console.log('键盘高度')
console.log(res.height)
if (res.height == 0) {
this.commentFocus = false
this.noticeFocus = false
}
})
},

更多关于uni-app 监听软键盘高度问题:使用HBuilderX运行时正常,打包为APP后失效的实战教程也可以访问 https://www.itying.com/category-93-b0.html

8 回复

提供一个完整点的示例页面 我们这边测试验证下

更多关于uni-app 监听软键盘高度问题:使用HBuilderX运行时正常,打包为APP后失效的实战教程也可以访问 https://www.itying.com/category-93-b0.html


进入不了 方法内

创建一个新的项目可以正常使用,有没有相关的配置和onKeyboardHeightChange 关联

回复 5***@qq.com: 没有相关配置 你可以试下新建的项目云打包后运行是否正常

回复 DCloud_Android_ST: 新建项目云打包正常,这个是有什么可能会影响呢

onReady() { uni.showToast({ title: ‘onReady’, icon: ‘none’ }) uni.onKeyboardHeightChange(res => { console.log(‘键盘高度’) console.log(res.height) uni.showToast({ title: ‘键盘高度’, icon: ‘none’ }) if (res.height == 0) { this.commentFocus = false } else { this.commentFocus = true } this.inputHeight = res.height }) },

我也出现这个问题了

在uni-app中,监听软键盘高度在HBuilderX运行正常但打包后失效,通常是由于平台差异和生命周期问题导致的。以下是关键点分析:

  1. 平台差异uni.onKeyboardHeightChange 在H5和部分Android模拟器上可能表现不一致,真机环境(尤其是iOS)可能有不同行为。

  2. 生命周期问题onShow 中注册监听可能不是最佳实践。建议在 onLoadmounted 中注册,并在 onUnloadbeforeDestroy 中移除监听,避免内存泄漏:

    onLoad() {
      this.keyboardListener = uni.onKeyboardHeightChange(res => {
        console.log('键盘高度:', res.height);
        if (res.height === 0) {
          this.commentFocus = false;
        }
      });
    },
    onUnload() {
      if (this.keyboardListener) {
        this.keyboardListener.off(); // 移除监听
      }
    }
    
  3. CSS调整问题:代码中通过 commentFocus 控制底部位置,但软键盘弹出时可能影响布局。确保 adjust-position="false" 已设置(代码中已存在),但需注意部分Android机型可能忽略此属性。

  4. 真机调试建议:使用自定义基座打包测试,确认真机上的控制台输出。如果高度始终为0,可能是机型兼容问题,可尝试备用方案:

    // 使用窗口尺寸变化间接监听
    uni.onWindowResize(res => {
      if (res.deviceOrientation === 'portrait') {
        // 通过窗口高度变化推断键盘状态
      }
    });
回到顶部