Ionic3/Angular应用中cordova-plugin-ionic-keyboard致布局崩溃问题
解决Ionic3/Angular中键盘弹出后布局崩溃的问题
我之前在做Ionic3项目时也碰到过一模一样的键盘布局崩溃问题,试了各种Resize设置都不管用,最后从CSS和事件监听入手解决了。结合你的情况,给你几个具体的排查和解决方向:
先排查自定义CSS的适配问题
看你用了.login-grid、.wrapper这些自定义类,很大概率是固定高度或者定位导致的适配问题:- 把
.login-grid的height: 100%或者height: 100vh改成flex: 1,让它自适应ion-content的可用空间——毕竟ion-content本身是滚动容器,内部元素用flex布局才是Ionic的正确姿势 - 检查
.wrapper类有没有硬编码的高度,改成min-height或者让内容自动撑开,避免键盘弹出时视口高度缩小导致元素挤压 - 避免给页面元素用
position: fixed,如果必须用,一定要监听键盘高度变化动态调整位置
- 把
手动监听键盘事件强制调整布局
有时候插件的自动Resize模式就是不生效,这时候手动监听键盘事件是最靠谱的:
首先确保你已经引入了Keyboard插件,然后在页面组件里这么写:import { Keyboard } from '@ionic-native/keyboard'; import { Platform } from 'ionic-angular'; import { Subscription } from 'rxjs/Subscription'; export class LoginPage { private keyboardShowSub: Subscription; private keyboardHideSub: Subscription; constructor(private keyboard: Keyboard, private platform: Platform) {} ionViewDidLoad() { this.platform.ready().then(() => { // 监听键盘弹出事件 this.keyboardShowSub = this.keyboard.onKeyboardShow().subscribe(res => { const kbHeight = res.keyboardHeight; // 给ion-content添加底部内边距,避免内容被键盘挡住 document.querySelector('ion-content').style.paddingBottom = `${kbHeight}px`; // 如果有底部按钮,也调整它的位置 // document.querySelector('.login-btn').style.bottom = `${kbHeight}px`; }); // 监听键盘收起事件,恢复布局 this.keyboardHideSub = this.keyboard.onKeyboardHide().subscribe(() => { document.querySelector('ion-content').style.paddingBottom = '0'; // document.querySelector('.login-btn').style.bottom = '0'; }); }); } // 页面销毁时取消订阅,防止内存泄漏 ionViewWillUnload() { if (this.keyboardShowSub) this.keyboardShowSub.unsubscribe(); if (this.keyboardHideSub) this.keyboardHideSub.unsubscribe(); } }调整config.xml的系统级配置
除了你试过的设置,再加上这些试试:<!-- Android上强制用adjustPan模式,避免页面缩放 --> <preference name="android-windowSoftInputMode" value="adjustPan" /> <!-- 禁用过度滚动,避免布局抖动 --> <preference name="DisallowOverscroll" value="true" /> <!-- 有的插件版本需要用none代替false来关闭Resize --> <preference name="KeyboardResizeMode" value="none" />检查ion-content的属性设置
给ion-content加上scrollEvents="true",确保它能响应视口变化自动滚动;另外如果之前设置过fixedContent="true",改成fixedContent="false",让内容可以自由滚动,这样键盘弹出时输入框会自动滚动到可视区域,减少布局崩溃的概率。
先从CSS排查开始,这是最常见的原因,如果还不行再试手动监听事件,一般都能解决问题。
内容的提问来源于stack exchange,提问作者Setu Kumar Basak
相关产品推荐
相关产品推荐

