【发布时间】:2017-04-10 16:50:12
【问题描述】:
我正在寻找一种简单的解决方案来检测移动设备上的键盘是否已打开/关闭(堆栈:Ionic2、Angular2)。
Ionic 是否将任何 'keyboard-open' 或 'keyboard-close' 类传播到 body/html 中?
【问题讨论】:
标签: javascript cordova angular ionic2
我正在寻找一种简单的解决方案来检测移动设备上的键盘是否已打开/关闭(堆栈:Ionic2、Angular2)。
Ionic 是否将任何 'keyboard-open' 或 'keyboard-close' 类传播到 body/html 中?
【问题讨论】:
标签: javascript cordova angular ionic2
键盘是移动设备原生的。所以你需要原生插件来检查它的功能。如下安装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();
}
【讨论】:
this.keyboard.onKeyboardShow() 必须在函数内部或将结果分配给属性。那么正确的方法是什么?
Ionic 不会发出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);
});
【讨论】: