You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cordova应用:解决键盘弹出后沉浸式模式失效及滚动问题

Cordova 键盘问题解决方案:输入框遮挡与沉浸式模式恢复

一、解决键盘弹出时输入框被遮挡、页面无法滚动的问题

  1. 修正 Viewport 配置
    确保index.html的viewport设置包含适配参数,避免页面布局异常:
<meta name="viewport" content="width=device-width, initial-scale=1.0, height=device-height, user-scalable=no, viewport-fit=cover">
  1. 调整键盘插件核心配置
    在config.xml中添加以下配置,启用页面滚动与收缩:
<preference name="KeyboardShrinksView" value="true" />
<preference name="KeyboardDisableScroll" value="false" />

注:KeyboardDisableScroll设为false才会允许页面随键盘滚动,若之前设为true会阻止滚动行为。

  1. CSS 兜底与手动滚动处理
    给页面容器设置基础滚动属性,确保输入框区域可滚动:
body {
    min-height: 100vh;
    overflow-y: auto;
    padding-bottom: env(safe-area-inset-bottom);
}

同时给输入框添加焦点监听,手动触发滚动确保输入框可见:

document.querySelectorAll('input, textarea').forEach(el => {
    el.addEventListener('focus', () => {
        setTimeout(() => {
            el.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }, 300);
    });
});

二、解决关闭Android键盘后退出沉浸式模式的问题

  1. 通过状态栏插件监听恢复沉浸式
    确保已安装cordova-plugin-statusbar,在deviceready事件中初始化并监听键盘状态:
document.addEventListener('deviceready', () => {
    // 初始设置沉浸式
    StatusBar.hide();
    StatusBar.overlaysWebView(true);

    // 键盘关闭时重新恢复沉浸式
    window.addEventListener('keyboardHide', () => {
        setTimeout(() => {
            StatusBar.hide();
            StatusBar.overlaysWebView(true);
        }, 100);
    });
}, false);
  1. 修改Android原生配置(兜底方案)
    在config.xml中添加窗口软输入模式配置,避免键盘弹出时破坏沉浸式布局:
<preference name="android-windowSoftInputMode" value="adjustResize|stateHidden" />

同时配置全屏主题,确保Activity默认处于全屏状态:

<platform name="android">
    <edit-config file="AndroidManifest.xml" target="/manifest/application/activity[@android:name='MainActivity']" mode="merge">
        <activity android:theme="@style/Theme.AppCompat.Light.NoActionBar.Fullscreen" />
    </edit-config>
</platform>

若自定义主题,需在res/values/styles.xml中定义:

<style name="Theme.AppCompat.Light.NoActionBar.Fullscreen" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>
</style>

额外注意

  • 确保插件为最新版本:执行cordova plugin update cordova-plugin-keyboard cordova-plugin-statusbar更新
  • 优先使用真实设备测试,模拟器键盘行为可能存在差异

内容的提问来源于stack exchange,提问作者CMaia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 20:25:14