uni-app 键盘弹出页面被顶起解决方案

在使用 uni-app 开发应用时,当键盘弹出时,页面会被顶起,导致页面底部的内容被遮挡。为了解决这个问题,可以尝试调整输入框的高度,并监听键盘的高度变化,在键盘弹出时动态调整输入框的位置,避免遮挡页面底部内容。

以下是解决方案的代码示例:

//键盘弹出相关
let screenHeight = uni.getSystemInfoSync().screenHeight;
let statusHeight= uni.getSystemInfoSync().statusBarHeight;
let inputHeight = screenHeight - statusHeight - 200;  // 修改输入框高度为200
// #ifdef APP-PLUS
inputHeight = screenHeight - statusHeight - 300;
// #endif
// #ifdef H5
inputHeight = 400;
// #endif

that.screenHeight = screenHeight - that.NavBar;
that.postheight = inputHeight;
//
//that.poststyle = 'height:200upx';
that.poststyle = 'height:'+inputHeight+'px';
that.readstyle = 'height:'+(inputHeight+30)+'px;white-space: pre-wrap;';
// #ifdef H5
//that.h5Keyboard();
// #endif
// #ifdef APP-PLUS
uni.onKeyboardHeightChange(res => {
    //监听软键盘的高度 
    //当点击软键盘自带的收起按钮的时候也就是会隐藏软键盘 这时候监听到的软键盘的高度就是0 、
    //让输入框取消焦点 这时候再去输入内容的时候 输入框就会弹起
    if (res.height == 0) {
        that.focalize(res.height);
        that.poststyle = 'height:'+inputHeight+'px';
    } else {
        // 让输入框位置上移,不遮挡最底部的内容
        var keyHeight = inputHeight - res.height;
        that.focus(res.height);
        that.poststyle = 'height:'+keyHeight+'px';
    }
});
// #endif

代码解析:

  1. 调整输入框高度:inputHeight 的值修改为 200,降低输入框的高度,减少页面被顶起的高度。
  2. 监听键盘高度变化: 使用 uni.onKeyboardHeightChange 方法监听键盘高度的变化,当键盘弹出或隐藏时,会触发回调函数。
  3. 动态调整输入框位置: 在回调函数中,获取键盘的高度,并计算出输入框需要上移的高度,从而实现输入框位置的动态调整,避免遮挡页面底部内容。

注意:

  • 以上代码仅供参考,实际应用中需要根据具体情况进行调整。
  • 除了调整输入框高度外,还可以通过其他方式来避免页面被顶起,例如使用 position: fixed 将输入框固定在页面底部,或者使用 overflow-y: scroll 让页面可以滚动。
  • 在使用 uni.onKeyboardHeightChange 方法时,需要确保在页面卸载时移除监听事件,避免内存泄漏。

希望以上解决方案能够帮助你解决 uni-app 键盘弹出页面被顶起的问题。

uni-app 键盘弹出页面被顶起解决方案

原文地址: https://www.cveoy.top/t/topic/n3vC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录