用于解决软键盘遮挡输入框问题。
此指令非我原创的(原址不容易打开,我这说明整理一下),仅适用于ios,不过对于android来说没有大关系,因为android通过配置config.xml就能调整软键盘,如下:
<preference name="Fullscreen" value="false" />
<preference name="android-windowSoftInputMode" value="adjustPan" />
现在开始实现这个指令,新建指令之前添加Keyboard插件,一般我们的项目默认已经装上了的,我们只需安装相应的ionic-native子模块:
npm install @ionic-native/keyboard --save
然后创建指令:
ionic g directive keyboardAttach
然后打开文件,修改为:
import { Directive, ElementRef, Input, OnDestroy, OnInit } from '@angular/core';
import { Keyboard } from '@ionic-native/keyboard';
import { Content, Platform } from 'ionic-angular';
import { Subscription } from 'rxjs/Subscription';
/**
* @name KeyboardAttachDirective
* @source https://gist.github.com/Manduro/bc121fd39f21558df2a952b39e907754
* @description
* The `keyboardAttach` directive will cause an element to float above the
* keyboard when the keyboard shows. Currently only supports the `ion-footer` element.
*
* ### Notes
* - This directive requires [Ionic Native](https://github.com/driftyco/ionic-native)
* and the [Ionic Keyboard Plugin](https://github.com/driftyco/ionic-plugin-keyboard).
* - Currently only tested to work on iOS.
* - If there is an input in your footer, you will need to set
* `Keyboard.disableScroll(true)`.
*
* @usage
*
* ```html
* <ion-content #content>
* </ion-content>
*
* <ion-footer [keyboardAttach]="content">
* <ion-toolbar>
* <ion-item>
* <ion-input></ion-input>
* </ion-item>
* </ion-toolbar>
* </ion-footer>
* ```
*/
@Directive({
selector: '[keyboardAttach]' // Attribute selector
})
export class KeyboardAttachDirective implements OnInit, OnDestroy {
@Input('keyboardAttach') content: Content;
private onShowSubscription: Subscription;
private onHideSubscription: Subscription;
constructor(
private elementRef: ElementRef,
private keyboard: Keyboard,
private platform: Platform
) {}
ngOnInit() {
if (this.platform.is('cordova') && this.platform.is('ios')) {
this.onShowSubscription = this.keyboard.onKeyboardShow().subscribe(e => this.onShow(e));
this.onHideSubscription = this.keyboard.onKeyboardHide().subscribe(() => this.onHide());
}
}
ngOnDestroy() {
if (this.onShowSubscription) {
this.onShowSubscription.unsubscribe();
}
if (this.onHideSubscription) {
this.onHideSubscription.unsubscribe();
}
}
private onShow(e) {
let keyboardHeight: number = e.keyboardHeight || (e.detail && e.detail.keyboardHeight);
this.setElementPosition(keyboardHeight);
// setTimeout(()=>{
// window.scrollTo(0, 0) ;
// this.content.scrollToBottom(0);
// this.keyboard.disableScroll(true);
// });
};
private onHide() {
this.setElementPosition(0);
};
private setElementPosition(pixels: number) {
this.elementRef.nativeElement.style.paddingBottom = pixels + 'px';
this.content.resize();
}
}
接着使用前记得在相应模块引入指令即可,如不使用懒加载的,就在app.module.ts
里的declarations
添加。
最后如指令里面的注释写的使用即可:
<ion-content #content>
</ion-content>
<ion-footer [keyboardAttach]="content">
<ion-toolbar>
<ion-item>
<ion-input></ion-input>
</ion-item>
</ion-toolbar>
</ion-footer>
注:后来居然在文档config项发现下面这个(以前没有的),我还没去验证效果,有兴趣可试一下: