簡體   English   中英

在 Angular 中頁面加載(模式顯示)后關注輸入后,在 Safari iOS 中顯示鍵盤

[英]displaying keyboard in Safari iOS after focus on input after page loads (modal shows) in Angular

在頁面加載或顯示輸入模式后,我需要設置焦點並打開鍵盤。

簡單的 .focus() 適用於 Android 和 iPad 的橫向模式。 但是在縱向模式和 iPhone 上設置了焦點但未顯示鍵盤。

我還嘗試了添加和關注附加元素的解決方案,但它不適用於 Angular。 IOS在輸入焦點上顯示鍵盤

@ViewChild('searchBarInput') searchBarInput: ElementRef;

  ngAfterViewInit(): void {
    setTimeout(()=> {
      this.searchBarInput.nativeElement.focus();
      this.searchBarInput.nativeElement.click();
    },180);
  }

測試應用: https ://inputfocus.vercel.app/

期望在頁面加載並設置焦點后,用戶可以開始輸入。 它是簡化版本 - 我在模態上需要這個,但在 iOS 上的行為是相似的

我想我找到了解決方案。 在 iOS (iphone) 和 iPad 縱向模式下,focus() 需要由用戶操作觸發。 因此,我們需要在使用顯示模態或帶有目標輸入字段的新 div 的單擊按鈕后立即進行設置。

我們可以自動創建這個新字段,設置焦點,並在將焦點移動到目標字段后將其移除。

單擊按鈕時,我們需要創建臨時輸入,附加到現有容器(靠近我們的輸入)並專注於它。

  btnClicked() {
      this.showModal = true; 
      
      this.searchBar = this.renderer2.selectRootElement('#searchBar', true);
     // 2nd argument preserves existing content

      // setting helper field and focusing on it
      this.inputHelper = this.renderer2.createElement('input');
      this.renderer2.appendChild(this.searchBar, this.inputHelper);
      this.inputHelper.focus();

      let event = new KeyboardEvent('touchstart',{'bubbles':true});            
      this.searchBarButton.nativeElement.dispatchEvent(event);
  }

在顯示模態/目標輸入后,我們移動焦點並刪除臨時的:

  initiateKeyboard() {       
    setTimeout(()=> {      
      this.searchBarInput.nativeElement.focus();     
      this.renderer2.removeChild(this.searchBar, this.inputHelper);
    },180);
  }

和模板:

<div id="searchBar"> 
  <input type="button" class="button is-link is-light" value="Search" (click)="btnClicked()" (touchstart)="initiateKeyboard()" #searchBarButton>
</div>

您只需要記住iPhone可能會縮放屏幕,因此您需要調整臨時輸入的參數。

工作解決方案: https ://inputfocus.vercel.app/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM