我正在寻找一个简单的解决方案来检测移动设备上的键盘是否已打开/关闭(堆栈:Ionic2,Angular2)。
Ionic是否将任何“键盘打开”或“键盘关闭”类传播到body / html中?
键盘是移动设备的原生。所以你需要本机插件来检查它的功能。安装cordova插件和离子原生类型如下
ionic plugin add ionic-plugin-keyboard
npm install --save @ionic-native/keyboard
添加以下代码行以检查键盘是否打开和关闭
import { Keyboard } from '@ionic-native/keyboard';
constructor(private keyboard: Keyboard) {
...
//Observes when the keyboard is shown
this.keyboard.onKeyboardShow();
//Observes when the keyboard is hidden
this.keyboard.onKeyboardHide();
}
离子不会发出keyboard-open
或keyboard-close
,但有ionic-plugin-keyboard就是这样。它会引发native.keyboardshow
和native.keyboardhide
事件。您还可以查询Keyboard.isVisible
属性。
丑陋的答案,但工作就像魅力:
import {NgZone} from '@angular/core';
public IsKeyboardOpen:boolean=false;
constructor(public ngZ:NgZone)
{
var innerHeight=window.innerHeight;
window.onresize = (e) =>
{
this.ngZ.run(() =>
{
if(window.innerHeight< innerHeight)
{
this.IsKeyboardOpen=true;
}
else
{
this.IsKeyboardOpen=false;
}
});
};
}
试试这个插件:https://ionicframework.com/docs/native/keyboard/
window.addEventListener('keyboardWillShow', (event) => {
// Describe your logic which will be run each time when keyboard is about to be shown.
console.log(event.keyboardHeight);
});