2016-01-14 13 views
1

我正在嘗試使用javascript函數focus(),但它在safari mobile上不起作用。我該如何解決這個問題?爲什麼iOS手機無法使用焦點()

<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

我與Angular應用程序有同樣的問題,我用一個非常簡單的黑客解決了它。

對於初學者,您可能想要使用jQuery;它爲您提供了許多明確的內容,並且或多或少地得到全面支持。然後,嘗試這樣做:

$(document).ready(function() { 

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

}); 

現在,我不完全知道它是如何工作的;也許一些渲染問題。但它確實有效。

如果你想VanillaJS:

window.onload = function() { 

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

} 

我不知道,如果VanillaJS版本將正常工作。

+0

只是好奇爲什麼這個答案被否決了?是因爲它沒有用嗎? –

+0

我不知道自己。 – weirdpanda

2

由於安全原因,iOS不允許自動觸發.focus()

相關問題