Javascript 为什么iOS mobile无法使用focus()

Javascript 为什么iOS mobile无法使用focus(),javascript,html,mobile-safari,Javascript,Html,Mobile Safari,我试图使用javascript函数focus(),但它在safari mobile上不起作用。如何解决此问题 <html lang="en"> <head> <meta charset="UTF-8"> <title>demo</title> <script type="text/javascript"> window.onload=function() {

我试图使用javascript函数
focus()
,但它在safari mobile上不起作用。如何解决此问题

<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>demo</title>
      <script type="text/javascript">
         window.onload=function() {
           document.getElementById('username').focus();
         }
      </script>
   </head>
   <body>
     <input type="text" id="username" >
     <input type="text" >
   </body>
</html>

演示
window.onload=function(){
document.getElementById('username').focus();
}

我在Angular应用程序中遇到了同样的问题,我用一个非常简单的方法解决了这个问题

对于初学者,您可能希望使用jQuery;它为您提供了很多明确的信息,并且或多或少得到了充分支持。然后,尝试这样做:

$( document ).ready( function() {

    setTimeout( $( '#username' ).focus(), 0 );

});
现在,我不知道它是如何工作的;可能是一些渲染问题。但它确实有效

如果您想要VanillaJS:

window.onload = function() {

    setTimeout( document
                  .getElementById( 'username' ).focus(), 0 );

}

我不知道VanillaJS的版本是否有效

iOS不允许出于安全原因自动触发
.focus()

只是好奇为什么这个答案被否决了?是因为它不起作用吗?我自己也不知道。这个说法有官方参考吗?