Ionic 4 клавиатура покрывает поле ввода - PullRequest
0 голосов
/ 12 февраля 2019

У меня есть приложение Ionic 4, в котором есть форма с входами.
Когда пользователь нажимает на вход, он открывает клавиатуру, но скрывает содержимое без прокрутки.
Есть ли способ?вокруг этого?

Это мой код:

<form #f="ngForm" (ngSubmit)="sendMail()">
   <ion-item>
     <ion-label position="floating">name
     </ion-label>
     <ion-input [(ngModel)]="senderName">
     </ion-input>
   </ion-item>

   <ion-item>
      <ion-label position="floating">mail
      </ion-label>
      <ion-input [(ngModel)]="senderMail">
      </ion-input>
    </ion-item>

    <ion-item class="borderedTextArea">
      <ion-textarea [(ngModel)]="mailText" style="height:150px;"></ion-textarea>
    </ion-item>

    <ion-button type="submit" style="float:left">send</ion-button>

</form>

Ответы [ 3 ]

0 голосов
/ 09 мая 2019

У меня тоже была эта проблема, но только в Android, я создал сценарий, который получал бы высоту сфокусированного элемента и клавиатуры, и с помощью jQuery я добавил marginTop для перемещения тела над клавиатурой, когдапоказывает клавиатура, это мой код:

constructor(
    private platform: Platform,
    private keyboard: Keyboard
  ) {
    if(this.platform.is('android')){
      this.keyboard.onKeyboardShow().subscribe((e) => {
        const offset = $(document.activeElement).offset().top;
        let height = (offset - e.keyboardHeight)*-1;
        height = height > 0 ? 0 : height;      
        $('body').animate({ 'marginTop': height + 'px' }, 100);
      });
      this.keyboard.onKeyboardHide().subscribe(e => {
        $('body').animate({ 'marginTop': 0 + 'px' }, 100);
      });
    }
}

необходимые библиотеки:

    npm install jquery
    npm install @types/jquery
    ionic cordova plugin add cordova-plugin-ionic-keyboard
    npm install @ionic-native/keyboard

импорт

    import { Platform } from '@ionic/angular';
    import * as $ from "jquery";
    import { Keyboard } from '@ionic-native/keyboard/ngx';

Не элегантное решение, но оно работает

0 голосов
/ 14 мая 2019

В настоящее время я использую Ionic4 с Cordova 9 и всеми последними пакетами, и я не смог найти какие-либо настройки в рамках, которые работали для меня.В конце концов я сделал этот обходной путь, который полностью обходит каркас.Он имеет небольшую анимацию и выглядит довольно хорошо, поэтому я использую его, пока фреймворк не решит это правильно.

global.scss

ion-app {
    /*animation of native keyboard show*/
    transition: margin 300ms;
}

app.component.ts

declare var $: any;

ngAfterViewInit() {
    // This element never changes.
    let ionapp = document.getElementsByTagName("ion-app")[0];

    window.addEventListener('keyboardDidShow', async (event) => {
        // Move ion-app up, to give room for keyboard
        let kbHeight: number = event["keyboardHeight"];
        let viewportHeight: number = $(window).height();
        let inputFieldOffsetFromBottomViewPort: number = viewportHeight - $(':focus')[0].getBoundingClientRect().bottom;
        let inputScrollPixels = kbHeight - inputFieldOffsetFromBottomViewPort;

        // Set margin to give space for native keyboard.
        ionapp.style["margin-bottom"] = kbHeight.toString() + "px";

        // But this diminishes ion-content and may hide the input field...
        if (inputScrollPixels > 0) {
            // ...so, get the ionScroll element from ion-content and scroll correspondingly
            // The current ion-content element is always the last. If there are tabs or other hidden ion-content elements, they will go above.
            let ionScroll = await $("ion-content").last()[0].getScrollElement();
            setTimeout(() => {
                $(ionScroll).animate({
                    scrollTop: ionScroll.scrollTop + inputScrollPixels
                }, 300);
            }, 300); // Matches scroll animation from css.
        }
    });
    window.addEventListener('keyboardDidHide', () => {
        // Move ion-app down again
        // Scroll not necessary.
        ionapp.style["margin-bottom"] = "0px";
    });
}
0 голосов
/ 04 апреля 2019

Я исправил эту Ионическую ошибку условно:

...
<ion-texarea (ionFocus)="fixTextareaBug()">
...

и в вашем .ts

@ViewChild(IonTextarea)
public ionTextArea: IonTextarea;
private focusFix = false;

...
...

public fixTextareaBug() {
  setTimeout(() => {
    if (this.focusFix) {
      this.focusFix = false;
      return;
    }
    (this.ionTextArea as any).el.lastElementChild.blur();
    this.focusFix = true;
    (this.ionTextArea as any).el.lastElementChild.focus();
  }, TEXTAREA_TIMEOUT);
}

Надеюсь, это решило вашу проблему

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...