我想我找到了解决方案。
在 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/ https://inputfocus.vercel.app/