目标:
重定向后将第一个输入框背景颜色更改为绿色(在 target.html 上)。如果您在 Google Chrome 中明确转到链接(将其输入 URL 栏),它就会起作用。
我使用的是这个版本的谷歌浏览器: 13.0.782.112
在这方面很难使用 jFiddle,因此我将使用内容分发网络 (CDN) jQuery 文件为您提供代码,以方便您使用。
查看此问题了解更多详情:
Why doesn't initial page focus change input field to Green on Google Chrome?
源页面:
(将此页面命名为 source.html)
<html>
<head>
</head>
<body>
<a href="./target.html">click this hyperlink in Google Chrome and see if the background-color changes to green on the first input field on target.html</a>
</body>
</html>
目标页面:
(将此页面命名为 target.html 并放在与 source.html 文件相同的文件夹中)
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
function Change(obj, evt) {
if (evt.type == "focus") {
$(obj).css('border-color', '#000000');
$(obj).css('background-color', '#90EE90');
}
else if (evt.type == "blur") {
$(obj).css('border-color', '#FFFFFF');
$(obj).css('background-color', '#7AC5CD');
}
}
$(document).ready(function() {
$("#Txt1").focus();
});
</script>
<style type="text/css">
.InputField
{
color: black;
font-size: 12px;
font-weight: bold;
background-color: #7AC5CD;
}
</style>
</head>
<body>
<input id="Txt1" runat="server" class="InputField" onfocus="Change(this, event)" onblur="Change(this, event)" /><br />
<input id="Txt2" runat="server" class="InputField" onfocus="Change(this, event)" onblur="Change(this, event)" /><br />
<input id="Txt3" runat="server" class="InputField" onfocus="Change(this, event)" onblur="Change(this, event)" /><br />
</body>
</html>
最佳答案
最好的办法是动态绑定(bind)那些 onfocus
和 onblur
事件,而不是在 HTML 中对它们进行硬编码。像这样:
$(document).ready(function() {
// bind the events
$('#Txt1, #Txt2, #Txt3').focus(function() {
$(this).css('border-color', '#000000');
$(this).css('background-color', '#90EE90');
}).blur(function() {
$(this).css('border-color', '#FFFFFF');
$(this).css('background-color', '#7AC5CD');
});
// trigger the first focus event
$('#Txt1').focus();
});
此代码应替换所有当前的 JavaScript,以及那些输入框上的 onfocus
和 on blur
属性。
对于您当前的解决方案,jQuery 或 Chrome(或两者)中似乎存在与触发事件相关的错误,这些事件绑定(bind)在 HTML 中而不是通过 JavaScript。无论出于何种原因,发生的情况是 DOMContentLoaded
事件作为“evt”变量而不是 onfocus
事件传递。
如果您有兴趣进一步研究该错误,甚至可能提交错误报告,您可以通过将 window.console.log(evt);
语句添加到Change 函数的第一行。然后打开 WebKit Web Inspector 并查看控制台,您会在那里看到 Event 对象,您会注意到它的类型是“DOMContentLoaded”,尽管它实际上应该是“focus”。
关于jquery - 为什么页面 jQuery .focus 事件在重定向后不会在 Google Chrome 中将背景颜色样式更改为绿色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7004143/