2014年1月28日 星期二

focus焦點於textbox在IE中失效之問題

這算是一個小記錄,起因是在Page Load的時候有的textbox要用JavaScript來做focus,但發現IE只要點選頁面其他元素時,在按F5(重新整理),則focus就會失效:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js "></script>
</head>
<body>
<input id="txtName" type="text" />
</body>
<script type="text/javascript">
$('#txtName').focus();
</script>
</html>


以上程式在Firefox和Chome都沒問題,但在IE Reflash就會失效,看起來好像IE載入元素、JavaScirpt的順序跟其他瀏覽器不太一樣(待確認),導致focus()事件在html document完成之前就先載入了,所以發現主控台會有以下錯誤


image


最後解決的方式是加個timeout,延遲執行focus

<script type="text/javascript">
setTimeout(function () {
$('#txtName').focus();
}, 500);
</script>

沒有留言:

張貼留言