2011-04-24 46 views
14

我想讓一個特定的表單域在iPhone上的Safari瀏覽器中自動獲取焦點。我認爲這將是非常直接的,但我沒有設法得到這個工作。那麼,這實際上是不可能的,還是我錯過了一些超顯而易見的東西(我懷疑)?下面是我使用的代碼:如何在iPhone Safari中的表單字段上自動對焦?

<!DOCTYPE html> 
<html> 
<head> 
<script type="text/javascript"> 
    function formfocus() { 
     document.getElementById('element').focus(); 
    } 
    window.onload = formfocus; 
</script> 
</head> 
<body> 

<form> 
<input/> 
<input id="element" autofocus/> 
<input/> 
</form> 

</body> 
</html> 

你可以看到我想要獲得焦點兩次,一次通過js和通過輸入字段中的HTML「aufofocus」屬性一次。這個伎倆也沒有。這在桌面瀏覽器上可以工作,但是當我在iPhone 4上打開頁面時,沒有骰子,也就是說,我必須通過單擊某個表單域來手動設置焦點。

最後,我想要的是打開手機瀏覽器的網站,並有側重於表單域,包括打開了,開始敲擊鍵盤。

感謝您的幫助!

回答

13

this page,自動對焦是不是在iPhone/iPad的支持可用性的原因。

0

儘量給輸入元素的類型

<input type="email" id="element" autofocus/> 

和後備您可以使用

<script type="text/javascript"> 
    if (!("autofocus" in document.createElement("input"))) { 
     document.getElementById("element").focus(); 
    } 
</script> 
+1

感謝Husar爲此,我已經更新了相應的代碼(在上面的URL處),但不幸的是它仍然無法在iPhone 4上運行=/ – pixelphantom 2011-04-24 17:06:02

+0

不知道爲什麼,它應該工作,查看這篇文章以獲取更多信息選項=> http://diveintohtml5.org/forms.html你會發現你需要在自動對焦領域 – Maverick 2011-04-24 17:24:05

+0

@Husar它不支持移動Safari - http://wufoo.com/html5/attributes/02-autofocus。 html – Connor 2012-08-05 22:43:14

-1

嘗試setTimeout()內部的.focus()。

setTimeout(function() { 
jQuery('#element').focus(); 
}, 500); 

我希望,這將是所有工作。

+0

試過了,不起作用。 – 3zzy 2017-01-08 23:13:15

+0

這不起作用,特別是當你使用'timeout'時。在某些情況下可以工作,但僅限於不使用超時。 – Sayed 2017-03-02 10:54:20