why iOS mobile cannot use focus()

[亡魂溺海] 提交于 2019-12-11 12:37:52

问题


I'm trying to use the javascript function focus(), but it does not work on safari mobile. How do I fix this problem?

<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>

回答1:


iOS does not allow .focus() to be fired automatically for security reason.




回答2:


I was having the same problem with an Angular app, and I solved it with a very simple hack.

For starters, you might want to use jQuery; it makes a lot of things clear-cut for you and is more-or-less fully supported. Then, try doing this:

$( document ).ready( function() {

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

});

Now, I don't exactly know how it works; maybe some rendering issue. But it works for sure.

If you want VanillaJS:

window.onload = function() {

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

}

I don't know if the VanillaJS version will work.



来源:https://stackoverflow.com/questions/34784499/why-ios-mobile-cannot-use-focus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!