问题
I've got a fairly complex web app which I've condensed down to the following two HTML pages, and the problem still exists. The problem? The thickbox modal's (iframe) input field loses focus after a second (or less) in IE (8 & 9). It only occurs when it's in the modal. If you load the page on its own, focus is not lost.
I've tried both jQuery 1.4.2 and 1.7.2, and the issue occurs with each. I'd set this up as jsfiddle but don't think it supports being able to trigger a second page. Have set it up so you can see it working here
Base page:
<!DOCTYPE HTML>
<html>
<head>
<link href="http://jquery.com/demo/thickbox/thickbox-code/thickbox.css" media="screen" rel="stylesheet" type="text/css" >
</head>
<body>
<a id="createAccountLink" class="thickbox" href="test2.html?KeepThis=true&TB_iframe=true&height=400&width=600">Login</a>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://jquery.com/demo/thickbox/thickbox-code/thickbox.js"></script>
</body>
</html>
Modal:
<html>
<head>
</head>
<body>
<input type="text" id="ContactFormName" name="firstName" class="text" value="" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$("#ContactFormName").focus();
</script>
</body>
</html>
If I was building this from scratch, I wouldn't use thickbox. But changing it isn't really an option right now since it's heavily used elsewhere.
Answer The focus has to be delayed. Even 1ms works.
setTimeout (function () {
$("#ContactFormName").focus();
}, 1);
回答1:
The focus has to be delayed. Even 1ms works.
setTimeout (function () {
$("#ContactFormName").focus();
}, 1);
回答2:
For ASP.NET i've created an extension method:
public static void FocusDelayed(this WebControl control, Page page)
{
ScriptManager.RegisterStartupScript(page, page.GetType(), "focusDelayed", "setTimeout (function () { document.getElementById(\"" + control.ClientID + "\").focus(); }, 500);", true);
}
So, in the onload Page_Load of the popup I call it
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
controleName.FocusDelayed(Page);
}
}
Hope it helps somebody.
Cheers
来源:https://stackoverflow.com/questions/11210552/ie-loses-focus-on-input-field-in-modal