我有一个简单的登录表单,其中包含 2 个输入字段:“用户名”和“密码”。 “用户名”字段默认聚焦。问题是,当用户在“用户名”或“密码”字段外单击时,焦点消失了(它既不在“用户名”上,也不在“密码”字段上)。我如何强制将焦点放在这两个字段上只有?
就我而言,这是一个非常烦人的行为,所以我真的很想这样做:)
我可以做类似的事情吗:
$("*").focus(function() {
if (!$(this).hasClass("my_inputs_class")) {
// How to stop the focusing process here ?
}
});
?
最佳答案
听起来您总是希望您的输入之一是有焦点的,这很公平。我这样做的方法是绑定(bind)您的每个输入 blur()
事件,这样如果它发生,它就会转到下一个元素。
这是标记:
<body>
<form method="POST" action=".">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" name="submit" />
</form>
</body>
这是 jQuery:
$(document).ready(function() {
// what are the named fields the user may focus on?
var allowed = ['username', 'password', 'submit'];
$.each(allowed, function(i, val) {
var next = (i + 1) % allowed.length;
$('input[name='+val+']').bind('blur', function(){
$('input[name='+allowed[next]+']').focus();
});
});
$('input[name='+allowed[0]+']').focus();
});
关于javascript - 如何不失去对登录页面的关注,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3015199/